gpt4 book ai didi

ios - 在上传到 Parse as PFFile 之前如何压缩或减小图像的大小? ( swift )

转载 作者:IT王子 更新时间:2023-10-29 04:57:41 24 4
gpt4 key购买 nike

我试图在直接在手机上拍照后将图像文件上传到 Parse。但它抛出一个异常:

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

这是我的代码:

在第一个 View Controller 中:

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

在上传图片的 View Controller 中:

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

关于ios - 在上传到 Parse as PFFile 之前如何压缩或减小图像的大小? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29726643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com