在上传到 Parse 作为 PFFile 之前,如何压缩或减小图像的大小?(迅速) [英] How to compress of reduce the size of an image before uploading to Parse as PFFile? (Swift)
问题描述
我试图在直接在手机上拍照后将图像文件上传到 Parse.但它抛出了一个异常:
I was trying to upload an image file to Parse after taking photo directly on phone. But it throws an exception:
由于未捕获的异常NSInvalidArgumentException"而终止应用,原因:PFFile 不能大于 10485760 字节"
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'PFFile cannot be larger than 10485760 bytes'
这是我的代码:
在第一个视图控制器中:
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`
但我仍然需要将那张照片上传到 Parse.有没有办法减小图片的尺寸或分辨率?
But I still need to upload that photo to Parse. Is there any way to reduce the size or resolution of the image?
推荐答案
是的,您可以使用 UIImageJPEGRepresentation
而不是 UIImagePNGRepresentation
来减小图像文件的大小.您可以创建一个扩展 UIImage 如下:
Yes you can use UIImageJPEGRepresentation
instead of UIImagePNGRepresentation
to reduce your image file size. You can just create an extension UIImage as follow:
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 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)
}
}
<小时>
编辑/更新:
edit/update:
Xcode 10 Swift 4.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 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 jpegData(compressionQuality: jpegQuality.rawValue)
}
}
<小时>
用法:
if let imageData = image.jpeg(.lowest) {
print(imageData.count)
}
这篇关于在上传到 Parse 作为 PFFile 之前,如何压缩或减小图像的大小?(迅速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!