-1

UIImageJPEGRepresentation is great function to downgrade the image.

I am just looking for downgrade the image to 1MB.

Yes there is a loopy way that we can apply multiple check until we receive 1024KB data count.

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

Any elegant solution please?

Ramesh
  • 147
  • 1
  • 17

1 Answers1

2

You can create a function

 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
    }
}
Do2
  • 1,751
  • 1
  • 16
  • 28
  • `let compressionValue = CGFloat(1024 / size)` Do's Magic – Ramesh Jun 13 '18 at 10:29
  • great answer, but for some reason I was getting the compressionValue 0 all the time, and I solved it by this Double(size), so this line would be: let compressionValue = CGFloat(1024 / Double(size)) – WaleedAmmari Jun 27 '19 at 21:23