JDG
JDG

Reputation: 540

NSData to UIImage back to NSData resulting length size tripled

I am doing a simple image file size reduction task but got this issue. When using no-loss option for JPEGs, the file size tripled then the original NSData for the image (same resolution). Any suggestion?

Here is the simple code:

let data = someImageData
print(data.length)
let image = UIImage(data: data)!
let newImageData = UIImageJPEGRepresentation(image, 1)
print(newImageData.length)
let newImageData = UIImageJPEGRepresentation(image, 0.8)
print(newImageData.length)

and output:

2604768  //original length
8112955  //new length if compression = 1
2588870  //new length if compression = 0.8

It seems I have to take the 0.8 quality loss to get the same data length. Did I miss something? Pease help.

Edit: I did some more test by converting the data to UIImage then to UIImageJPEGRepresentation(image, 1), the length size of the new data increases every cycle. But if I use UIImageJPEGRepresentation(image, 0.8), the length size of the new data decreases a bit (very little), however, the compound qualify loss should be a concern.

Upvotes: 2

Views: 613

Answers (1)

Kakshil Shah
Kakshil Shah

Reputation: 3796

What your code is doing is decompressing/extracting the image into memory with the line --> let image = UIImage(data: data)! and then recompressing as JPEG, with let newImageData = UIImageJPEGRepresentation(image, 1) with the highest quality ratio (q=1.0). That’s why the image is suddenly so big.

So the moment you get your image as an UIImage from NSData, the decompression/conversion changes the size of the image.

The image's file size will actually be 8112955.

Upvotes: 2

Related Questions