Downgrade UIImage to 1MB in swift

470 Views Asked by At

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?

1

There are 1 best solutions below

2
Do2 On BEST ANSWER

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