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

前端之家收集整理的这篇文章主要介绍了如何压缩缩小图像的大小,然后上传到Parse作为PFFile? (迅速)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我直接在手机上拍照后尝试上传一个图像文件到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)
}
原文链接:https://www.f2er.com/swift/320813.html

猜你在找的Swift相关文章