在 swift 中将 UIImage 降级为 1MB

Downgrade UIImage to 1MB in swift

UIImageJPEGRepresentation降级图片的好功能

我只是想将图像降级到 1MB

是的,有一种循环方式,我们可以应用多次检查,直到我们收到 1024KB 数据计数。

 let image = UIImage(named: "test")!
    if let imageData = UIImagePNGRepresentation(image) {
       let kb = imageData.count / 1024
          if kb > 1024 {
            let compressedData =  UIImageJPEGRepresentation(image, 0.2)!
      }
 }

有什么优雅的解决方案吗?

您可以创建一个函数

 func resize(image:UIImage) -> Data? {
    if let imageData = UIImagePNGRepresentation(image){ //if there is an image start the checks and possible compression
    let size = imageData.count / 1024
        if size > 1024 { //if the image data size is > 1024
        let compressionValue = CGFloat(1024 / size) //get the compression value needed in order to bring the image down to 1024
          return UIImageJPEGRepresentation(image, compressionValue) //return the compressed image data
        }
        else{ //if your image <= 1024 nothing needs to be done and return it as is
          return imageData
        }
    }
    else{ //if it cant get image data return nothing
        return nil
    }
}