Skip to content

Instantly share code, notes, and snippets.

@iAmrSalman
Created July 20, 2017 23:06
Show Gist options
  • Save iAmrSalman/bd095127ea2dfec47244b39360fee26f to your computer and use it in GitHub Desktop.
Save iAmrSalman/bd095127ea2dfec47244b39360fee26f to your computer and use it in GitHub Desktop.
[CompressionService] compress 'image' to 'maxSize' size #swift3 #image #compression
struct CompressionService {
/**
compress 'image' to 'maxSize' size
- Parameter image: The image to compress.
- Parameter maxSize: The maximum size in MB to image.
- Returns: A Data image with 'maxSize' applied.
*/
static func compress(image: UIImage, maxSize: CGFloat) -> Data? {
guard let imageSize = UIImageJPEGRepresentation(image, 1)?.count else { return nil }
let compressionRate: CGFloat = (maxSize * 1024) / CGFloat(imageSize)
return UIImageJPEGRepresentation(image, compressionRate)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment