【问题标题】:Downgrade UIImage to 1MB in swift迅速将 UIImage 降级到 1MB
【发布时间】:2018-06-13 09:25:08
【问题描述】:

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

请提供任何优雅的解决方案?

【问题讨论】:

标签: ios swift uiimage uiimagejpegrepresentation


【解决方案1】:

你可以创建一个函数

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

【讨论】:

  • let compressionValue = CGFloat(1024 / size) Do's Magic
  • 很好的答案,但由于某种原因,我一直得到compressionValue 0,我用这个Double(size)解决了它,所以这一行是:let compressionValue = CGFloat(1024 / Double (大小))
猜你喜欢
  • 2015-03-12
  • 1970-01-01
  • 2013-08-12
  • 2021-11-03
  • 1970-01-01
  • 1970-01-01
  • 2020-07-27
  • 2019-12-18
  • 2021-09-26
相关资源
最近更新 更多