Понижение UIImage до 1 МБ в быстром темпе - PullRequest
0 голосов
/ 13 июня 2018

UIImageJPEGRepresentation - отличная функция для понижения изображения.

Я просто хочу понизить изображение до 1MB .

Да, естьзацикленный способ, которым мы можем применить многократную проверку, пока мы не получим счетчик данных 1024 КБ.

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

Любое изящное решение, пожалуйста?

1 Ответ

0 голосов
/ 13 июня 2018

Вы можете создать функцию

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