Last active
January 24, 2020 17:23
-
-
Save PetreVane/64c5e06499eece0f77face2e676f4864 to your computer and use it in GitHub Desktop.
Helper method which scales down the size of an image, before being uploaded to Firebase Storage
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 UIImage { | |
// Usage: | |
// let scaledImage = image.scale(newWidth: 960.0) | |
func reduceImageSize(to newWidth: CGFloat) -> UIImage { | |
if self.size.width == newWidth { | |
return self | |
} | |
// Calculates the scaling factor | |
let scaleFactor = newWidth / self.size.width | |
let newHeight = self.size.height * scaleFactor | |
let newSize = CGSize(width: newWidth, height: newHeight) | |
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0) | |
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) | |
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return newImage ?? self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment