Skip to content

Instantly share code, notes, and snippets.

@iAmrSalman
Created July 20, 2017 18:04
Show Gist options
  • Save iAmrSalman/62f3b5ea2dd6e94ebfdd0320a9603d4f to your computer and use it in GitHub Desktop.
Save iAmrSalman/62f3b5ea2dd6e94ebfdd0320a9603d4f to your computer and use it in GitHub Desktop.
[Compress image] UIImage extension to enable image compression #swift3 #compression #image
extension UIImage {
enum JPEGQuality: CGFloat {
case lowest = 0
case low = 0.25
case medium = 0.5
case high = 0.75
case highest = 1
}
/// Returns the data for the specified image in PNG format
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
var png: Data? { return UIImagePNGRepresentation(self) }
/// Returns the data for the specified image in JPEG format.
/// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory.
/// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
func jpeg(_ quality: JPEGQuality) -> Data? {
return UIImageJPEGRepresentation(self, quality.rawValue)
}
}
if let imageData = image.jpeg(.lowest) {
print(imageData.count)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment