I created a new file UIImage+compress.swift and it's in the same directory as my PhotoController.swift. I was looking for ways to compress a image before storing it and I found the following link that explains the process: How to compress of reduce the size of an image before uploading to Parse as PFFile? (Swift)
I've tried to directly call UIImageJPEGRepresentation for the image but that doesn't get me anywhere. Tried making the extension method public hoping that'd solve the problem but that didn't work out either. I tried to look for similar questions in stackOverflow but they are different in that none explains why the method is not usable.
This is the code for extension method:
import UIKit
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 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(_ jpegQuality: JPEGQuality) -> Data? {
return UIImageJPEGRepresentation(self, jpegQuality.rawValue)
}
}
This is the code for PhotoController where I try to call the extension method:
class PhotoController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
... ...
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as String) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
var res = image.jpeg(.lowest) as! UIImage
if (newMedia == true) {
UIImageWriteToSavedPhotosAlbum(res,
self,
#selector(PhotoController.image(image:didFinishSavingWithError:contextInfo:)),
nil)
}
}
self.dismiss(animated: true, completion: nil)
}
}
I keep getting the error: Value of type 'UIImage' has no member 'compress'.
Also, how do I print the image size to make sure that it's indeed compressed?