Last active
July 3, 2021 19:05
-
-
Save romanmiller/9f4eac6c4cd8e156fd50b1382daa481f to your computer and use it in GitHub Desktop.
Compress image size (Swift)
This file contains hidden or 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
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