Skip to content

Instantly share code, notes, and snippets.

@ahmedAlmasri
Last active August 30, 2023 10:47
Show Gist options
  • Save ahmedAlmasri/da3fac872b914b187b17e85e1f3e87d6 to your computer and use it in GitHub Desktop.
Save ahmedAlmasri/da3fac872b914b187b17e85e1f3e87d6 to your computer and use it in GitHub Desktop.
ios swift Image compression
//: Playground - noun: a place where people can play
import UIKit
do{
func compressImage(_ img:UIImage) -> UIImage? {
// Reducing file size to a 10th
var actualHeight: CGFloat = img.size.height
var actualWidth: CGFloat = img.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.5
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)
img.draw(in: rect)
guard let img = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
guard let imageData = UIImageJPEGRepresentation(img, compressionQuality) else {
return nil
}
return UIImage(data: imageData)
}
//compressImage(UIImage(named: "tst.jpg")!)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment