Compress UIImage, but keep the size

I am trying to use UIImageView to show a photo. But Photography is sometimes a little big, and I want to compress it. But I would like to keep her size. For example, the photo is 4M and has a size of 320X480. And I want to compress it, and it can have 1M, but still has a size of 320X480.

thanks!

+4
source share
2 answers

Compression using JPEG compression.

 lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(highResImage, quality)]; 

Where quality is between 0.0 and 1.0

You should read the UIImage documentation , everything is explained there ...

+18
source

If your goal is to get an image below a certain data length, it's hard to guess what compression ratio you need unless you know that the original image will always be a certain data length. Here is a simple iterative approach that uses jpeg compression to achieve the target length ... say 1 MB to ask a question:

 // sourceImage is whatever image you're starting with NSData *imageData = [[NSData alloc] init]; for (float compression = 1.0; compression >= 0.0; compression -= .1) { imageData = UIImageJPEGRepresentation(sourceImage, compression); NSInteger imageLength = imageData.length; if (imageLength < 1000000) { break; } } UIImage *finalImage = [UIImage imageWithData:imageData]; 

I saw several approaches that use the while to compress the image by 0.9 or any other until the target size is reached, but I think that you will lose image quality and processor cycles by sequentially compressing / restoring the image. In addition, the for loop is a bit safer here, because it automatically stops after trying to compress as much as possible (zero).

+3
source

Source: https://habr.com/ru/post/1380999/


All Articles