1

I want to reduce the size of image like this website http://resizeimage.net my image is 1080 x 360 size 120kb after I used the code below but when I use the website I get 58kb or if there is a library or algorithm to compress JPEG file

func resizeImage(_ image: UIImage, newHeight: CGFloat) -> UIImage {
    let scale = newHeight / image.size.height
    let newWidth = image.size.width * scale
    UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
    image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    let imageData = UIImageJPEGRepresentation(newImage!, 0.5)! as Data
    UIGraphicsEndImageContext()
    return UIImage(data:imageData)!
}
Bensalem Ilyes
  • 29
  • 1
  • 1
  • 7

1 Answers1

5

The compression quality passed in to UIImageJPEGRepresentation determines the image quality your JPEG image will be. You have 0.5, try something lower like 0.1:

 let imageData = UIImageJPEGRepresentation(newImage!, 0.1)! as Data

From Apple's Docs:

compressionQuality: The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).

Mattia Righetti
  • 1,265
  • 1
  • 18
  • 31
rmooney
  • 6,123
  • 3
  • 29
  • 29
  • but when I put 0.1 the image will look very bad – Bensalem Ilyes Feb 22 '17 at 18:35
  • Yeah thats the tradeoff you get with image compression. You could try different values anywhere between 0.1 and 0.5 to see if any of them give you good enough quality and the file size you're looking for. Maybe 0.35 or 0.4 would be better. – rmooney Feb 22 '17 at 19:11