elvislkm elvislkm - 1 year ago 283
Swift Question

How to compress of reduce the size of an image before uploading to Parse as PFFile? (Swift)

I was trying to upload an image file to Parse after taking photo directly on phone. But it throws an exception:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'PFFile cannot be larger than 10485760 bytes'

Here is my code:

In first view controller:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "getImage")
var svc = segue.destinationViewController as! ClothesDetail
svc.imagePassed = imageView.image

In view controller that uploads image:

let imageData = UIImagePNGRepresentation(imagePassed)
let imageFile = PFFile(name: "\(picName).png", data: imageData)

var userpic = PFObject(className:"UserPic")
userpic["picImage"] = imageFile`

But I still need to upload that photo to Parse. Is there any way to reduce the size or resolution of the image?

Answer Source

Yes you can use UIImageJPEGRepresentation instead of UIImagePNGRepresentation to reduce your image file size. You can just create an extension UIImage as follow:

update: Xcode 7 • Swift 2.0

extension UIImage {
    var uncompressedPNGData: NSData      { return UIImagePNGRepresentation(self)!        }
    var highestQualityJPEGNSData: NSData { return UIImageJPEGRepresentation(self, 1.0)!  }
    var highQualityJPEGNSData: NSData    { return UIImageJPEGRepresentation(self, 0.75)! }
    var mediumQualityJPEGNSData: NSData  { return UIImageJPEGRepresentation(self, 0.5)!  }
    var lowQualityJPEGNSData: NSData     { return UIImageJPEGRepresentation(self, 0.25)! }
    var lowestQualityJPEGNSData:NSData   { return UIImageJPEGRepresentation(self, 0.0)!  }

Then you can use it like this:

let imageData = imagePassed.lowestQualityJPEGNSData