Skip to content

Instantly share code, notes, and snippets.

@floriangbh
Last active January 23, 2017 13:41
Show Gist options
  • Save floriangbh/724e4de855f75e4dbb5e5bdecdd0236e to your computer and use it in GitHub Desktop.
Save floriangbh/724e4de855f75e4dbb5e5bdecdd0236e to your computer and use it in GitHub Desktop.
Image compression
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