如何在上传到Parse之前压缩缩小图像的大小为PFFile? (迅速) [英] How to compress of reduce the size of an image before uploading to Parse as PFFile? (Swift)

查看:127
本文介绍了如何在上传到Parse之前压缩缩小图像的大小为PFFile? (迅速)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图直接在手机上拍照后将图像文件上传到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)
    }
}

用法:

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

这篇关于如何在上传到Parse之前压缩缩小图像的大小为PFFile? (迅速)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆