我直接在手机上拍照后尝试上传一个图像文件到Parse。但它抛出一个例外:
Terminating app due to uncaught exception ‘NSInvalidArgumentException’,reason: ‘PFFile cannot be larger than 10485760 bytes’
这里是我的代码:
在第一个视图控制器:
- override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) {
- if (segue.identifier == "getImage")
- {
- var svc = segue.destinationViewController as! ClothesDetail
- svc.imagePassed = imageView.image
- }
- }
- let imageData = UIImagePNGRepresentation(imagePassed)
- let imageFile = PFFile(name: "\(picName).png",data: imageData)
- var userpic = PFObject(className:"UserPic")
- userpic["picImage"] = imageFile`
但我仍然需要将这张照片上传到Parse。有没有办法减少图像的大小或分辨率?
是的,您可以使用UIImageJPEGRepresentation而不是UIImagePNGRepresentation来减少您的图像文件大小。您可以只创建一个扩展UIImage如下:
Xcode 8.2•Swift 3.0.2
- 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)
- }
Swift 2.3
- 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) }
- }
然后你可以这样使用它:
- if let imageData = image.lowestQualityJPEGNSData {
- print(imageData.length)
- }