Skip to content

Instantly share code, notes, and snippets.

@PetreVane
Last active January 24, 2020 17:23
Show Gist options
  • Save PetreVane/64c5e06499eece0f77face2e676f4864 to your computer and use it in GitHub Desktop.
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
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