Created
February 9, 2019 12:10
-
-
Save muratyasarr/7a82cc50281222a4b7ccd3bd8fd76f9b to your computer and use it in GitHub Desktop.
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
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