compress UIImage but keep size

2 Solutions Collect From Internet About “compress UIImage but keep size”

Compress it using the 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 in thereā€¦

If your goal is to get the image below a specific data length, it’s tough to guess what compression ratio you need, unless you know the source image will always be a certain data length. Here’s a simple iterative approach that uses jpeg compression to achieve a target length… let’s say 1MB, to match the 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’ve seen some approaches that use a while loop to compresses the image by .9 or whatever until the target size is met, but I think you’d be losing image quality and processor cycles by successively compressing/reconstituting the image. Also, the for loop here is a little safer because it stops automatically after trying the maximum possible compression (zero).