Last active
January 23, 2017 13:41
-
-
Save floriangbh/724e4de855f75e4dbb5e5bdecdd0236e to your computer and use it in GitHub Desktop.
Image compression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public extension UIImage { | |
func compress() -> UIImage? { | |
var actualHeight = self.size.height | |
var actualWidth = self.size.width | |
let maxHeight: CGFloat = 800.0 | |
let maxWidth: CGFloat = 800.0 | |
var imgRatio = actualWidth/actualHeight | |
let maxRatio = maxWidth/maxHeight | |
var compressionQuality: CGFloat = 0.6 | |
if actualHeight > maxHeight || actualWidth > maxWidth { | |
if imgRatio < maxRatio { | |
//Adjust width according to maxHeight | |
imgRatio = maxHeight / actualHeight | |
actualWidth = imgRatio * actualWidth | |
actualHeight = maxHeight | |
} else if imgRatio > maxRatio { | |
//Adjust height according to maxWidth | |
imgRatio = maxWidth / actualWidth | |
actualHeight = imgRatio * actualHeight | |
actualWidth = maxWidth | |
} else { | |
actualHeight = maxHeight | |
actualWidth = maxWidth | |
} | |
} else { | |
compressionQuality = 1 | |
} | |
// Draw | |
let rect = CGRect(x: 0, y: 0, width: actualWidth, height: actualHeight) | |
UIGraphicsBeginImageContext(rect.size) | |
self.draw(in: rect) | |
if let img = UIGraphicsGetImageFromCurrentImageContext(), | |
let imageData = UIImageJPEGRepresentation(img, CGFloat(compressionQuality)) { | |
UIGraphicsEndImageContext() | |
return UIImage(data: imageData) | |
} | |
UIGraphicsEndImageContext() | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment