how UIImageJPEGRepresentation() works

181 Views Asked by At

A 700x700 png image, shows imageview cost of 1.88Mib memory, but if I compress it with UIImageJPEGRepresentation(data, 0.9), the memory cost decreases to 736Kib but the image size unchanged, the jpg pixel has no alpha, but the cost of memory decrease almost 62%, I want to know how UIImageJPEGRepresentation() works? thx

load png image:

NSString *path = [[NSBundle mainBundle] pathForResource:@"bbb" ofType:@"png"];
NSData * data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:NULL];
UIImage * img = [UIImage imageWithData:data];

load jpg image

NSString *path = [[NSBundle mainBundle] pathForResource:@"bbb" ofType:@"png"];
NSData * data = [NSData dataWithContentsOfFile:path options:NSDataReadingMappedIfSafe error:NULL];
UIImage * img = [UIImage imageWithData:data];
img = [UIImage imageWithData:UIImageJPEGRepresentation(img, 0.9)];

jpg memory cost:

jpg memory cost

png memory cost:

png memory cost

1

There are 1 best solutions below

1
Codo On

UIImage imageWithData: will decompress the PNG file. The resulting size matches the resolution:

700 pixels × 700 pixels × 4 byte/pixel = 1,960,000 = 1.87 MByte

This image is no longer related with the PNG format and compression technique.

The second example first decompresses the PNG file and then compresses it using the JPEG algorithm. The result is ⁠– of course ⁠– smaller as it is compressed.

Both JPEG and PNG are algorithms for compressing images. You will find a lot of documentation online about how they work. It's far from trivial...