如何压缩缩小图像的大小,然后上传到Parse作为PFFile? (迅速)

前端之家收集整理的这篇文章主要介绍了如何压缩缩小图像的大小,然后上传到Parse作为PFFile? (迅速)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我直接在手机上拍照后尝试上传一个图像文件到Parse。但它抛出一个例外:

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

这里是我的代码

在第一个视图控制器:

  1. override func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject?) {
  2. if (segue.identifier == "getImage")
  3. {
  4. var svc = segue.destinationViewController as! ClothesDetail
  5. svc.imagePassed = imageView.image
  6. }
  7. }

在视图控制器中上传图片

  1. let imageData = UIImagePNGRepresentation(imagePassed)
  2. let imageFile = PFFile(name: "\(picName).png",data: imageData)
  3.  
  4. var userpic = PFObject(className:"UserPic")
  5. userpic["picImage"] = imageFile`

但我仍然需要将这张照片上传到Parse。有没有办法减少图像的大小或分辨率?

是的,您可以使用UIImageJPEGRepresentation而不是UIImagePNGRepresentation来减少您的图像文件大小。您可以只创建一个扩展UIImage如下:

Xcode 8.2•Swift 3.0.2

  1. extension UIImage {
  2. enum JPEGQuality: CGFloat {
  3. case lowest = 0
  4. case low = 0.25
  5. case medium = 0.5
  6. case high = 0.75
  7. case highest = 1
  8. }
  9.  
  10. /// Returns the data for the specified image in PNG format
  11. /// If the image object’s underlying image data has been purged,calling this function forces that data to be reloaded into memory.
  12. /// - 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.
  13. var png: Data? { return UIImagePNGRepresentation(self) }
  14.  
  15. /// Returns the data for the specified image in JPEG format.
  16. /// If the image object’s underlying image data has been purged,calling this function forces that data to be reloaded into memory.
  17. /// - 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.
  18. func jpeg(_ quality: JPEGQuality) -> Data? {
  19. return UIImageJPEGRepresentation(self,quality.rawValue)
  20. }
  21. }

用法

  1. if let imageData = image.jpeg(.lowest) {
  2. print(imageData.count)
  3. }

Swift 2.3

  1. extension UIImage {
  2. var uncompressedpnGData: NSData? { return UIImagePNGRepresentation(self) }
  3. var highestQualityJPEGNSData: NSData? { return UIImageJPEGRepresentation(self,1.0) }
  4. var highQualityJPEGNSData: NSData? { return UIImageJPEGRepresentation(self,0.75) }
  5. var mediumQualityJPEGNSData: NSData? { return UIImageJPEGRepresentation(self,0.5) }
  6. var lowQualityJPEGNSData: NSData? { return UIImageJPEGRepresentation(self,0.25) }
  7. var lowestQualityJPEGNSData:NSData? { return UIImageJPEGRepresentation(self,0.0) }
  8. }

然后你可以这样使用它:

  1. if let imageData = image.lowestQualityJPEGNSData {
  2. print(imageData.length)
  3. }

猜你在找的Swift相关文章