-1

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

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

4

1 回答 1

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
    }
}
于 2018-06-13T10:17:43.297 回答