KexAri
KexAri

Reputation: 3977

Reducing the quality of a UIImage (compressing it)

Hi I am trying to compress a UIImage my code is like so:

    var data = UIImageJPEGRepresentation(image, 1.0)
    print("Old image size is \(data?.length) bytes")
    data = UIImageJPEGRepresentation(image, 0.7)
    print("New image size is \(data?.length) bytes")
    let optimizedImage = UIImage(data: data!, scale: 1.0)

The print out is:

Old image size is Optional(5951798) bytes
New image size is Optional(1416792) bytes

Later on in the app I upload the UIImage to a webserver (it's converted to NSData first). When I check the size it's the original 5951798 bytes. What could I be doing wrong here?

Upvotes: 0

Views: 1480

Answers (2)

RJV Kumar
RJV Kumar

Reputation: 2408

Send this data to server data = UIImageJPEGRepresentation(image, 0.7), instead of sending optimizedimage to server.

You already compressed the image to data. So it will be repeating process(resetting to original size).

Upvotes: 0

Wain
Wain

Reputation: 119021

A UIImage provides a bitmap (uncompressed) version of the image which can be used for rendering the image to screen. The JPEG data of an image can be compressed by reducing the quality (the colour variance in effect) of the image, but this is only in the JPEG data. Once the compressed JPEG is unpacked into a UIImage it again requires the full bitmap size (which is based on the colour format and the image dimensions).

Basically, keep the best quality image you can for display and compress just before upload.

Upvotes: 2

Related Questions