Skip to content

Instantly share code, notes, and snippets.

@muratyasarr
Created February 9, 2019 12:10
Show Gist options
  • Save muratyasarr/7a82cc50281222a4b7ccd3bd8fd76f9b to your computer and use it in GitHub Desktop.
Save muratyasarr/7a82cc50281222a4b7ccd3bd8fd76f9b to your computer and use it in GitHub Desktop.
static func compressImage(image:UIImage) -> Data? {
// Reducing file size to a 10th
var actualHeight: CGFloat = image.size.height
var actualWidth: CGFloat = image.size.width
let maxHeight: CGFloat = 1136.0
let maxWidth: CGFloat = 640.0
var imgRatio: CGFloat = actualWidth/actualHeight
let maxRatio: CGFloat = maxWidth/maxHeight
var compressionQuality: CGFloat = 0.7
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
compressionQuality = 1
}
}
let rect = CGRect(x: 0.0, y: 0.0, width: actualWidth, height: actualHeight)
UIGraphicsBeginImageContext(rect.size)
image.draw(in: rect)
guard let img = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
let imageData = UIImageJPEGRepresentation(img, compressionQuality)
UIGraphicsEndImageContext()
return imageData
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment