一尘不染

在以PFFile格式上传到Parse之前如何压缩图像的大小?(迅速)

swift

直接在手机上拍照后,我试图将图像文件上传到Parse。但这会引发异常:

由于未捕获的异常“ NSInvalidArgumentException”而终止应用程序,原因:“ PFFile不能大于10485760字节”

这是我的代码:

在第一视图控制器中:

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。有什么方法可以减小图像的尺寸或分辨率?


阅读 214

收藏
2020-07-07

共1个答案

一尘不染

是的,你可以使用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 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)
    }
}

编辑/更新:

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)
}
2020-07-07