如何将 UIImage 保存到 Parse

How to save a UIImage to Parse

我拍摄了一张图片并将其转换为 jpeg 格式

let jpgImage = UIImageJPEGRepresentation(image1, 0.5)

接下来我想将此图像作为 PFUser 的对象部分上传到 Parse。每当我尝试这个时,我都会收到错误

[Error]: The object is too large -- should be less than 128 kB

我不知道如何解决这个错误,只能注册用户。感谢您的帮助或建议!

对象被限制为 128kb 作为错误状态,如果您的图像大于它,您可以选择使用下面的函数缩小它。

func ResizeImage(image: UIImage, targetSize: CGSize) -> UIImage {
    let size = image.size
    let widthRatio  = targetSize.width  / image.size.width
    let heightRatio = targetSize.height / image.size.height
    // Figure out what our orientation is, and use that to form the rectangle
    var newSize: CGSize
    if(widthRatio > heightRatio) {
        newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
    } else {
        newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)
    }

    // This is the rect that we've calculated out and this is what is actually used below
    let rect = CGRectMake(0, 0, newSize.width, newSize.height)

    // Actually do the resizing to the rect using the ImageContext stuff
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.drawInRect(rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

利用以上功能,您可以将图片动态调整大小 dimension.Here 如上代码调整200*200的图片大小。通过调用 下面的函数。

self.ResizeImage(UIImage(named: "yourImageName")!, targetSize: CGSizeMake(200.0, 200.0)) 

来自 here 的源代码。

所以首先检查图像大小:

let sizeOfImage = image?.size

if let image = image {
    let sizeOfImage = image.size
    // Check the size here and resize if needed
}