Skip to content

Instantly share code, notes, and snippets.

@romanmiller
Last active July 3, 2021 19:05
Show Gist options
  • Save romanmiller/9f4eac6c4cd8e156fd50b1382daa481f to your computer and use it in GitHub Desktop.
Save romanmiller/9f4eac6c4cd8e156fd50b1382daa481f to your computer and use it in GitHub Desktop.
Compress image size (Swift)
extension CGSize {
// get scale of image size with max dimention
public func scale(max: CGFloat) -> CGFloat {
if width > height{
if width > max {
return max / width
}
} else {
if height > max {
return max / height
}
}
return 1
}
}
extension UIImage {
// resize image with max dimention option
public func resize(to maxDimention: CGFloat) -> UIImage {
let aspect = self.size.scale(max: maxDimention)
let newHeight = self.size.height * aspect
let newWidth = self.size.width * aspect
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment