Compress UIImage to certain size in megabytes [dup

2019-03-30 18:33发布

问题:

This question already has an answer here:

  • image compression by size - iPhone SDK 6 answers

In obj-с how does one get the size of a certain UIImage stored in a custom NSMutableArray? That's the first thing I want to do. And the second is, knowing that the image is bigger in file size (say it's 15 MB) than my own file size limit (say it's 5 MB) how does one compress the image to be the closest to the file size limit, say 4.99 MB?

回答1:

i have seen this on another question on stacj overflow link is -- image compression by size - iPhone SDK

but i does combine two answer from there , i also used this code to do compression.

CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
int maxFileSize = 250*1024;

NSData *imageData = UIImageJPEGRepresentation(yourImage, compression);

while ([imageData length] > maxFileSize && compression > maxCompression)
{
    compression -= 0.1;
    imageData = UIImageJPEGRepresentation(yourImage, compression);
}

One way to do it, is to re-compress the file in a loop, until you find the desired size. You could first find height and width, and guess the compression factor (larger image more compression) then after you compress it, check the size, and split the difference again.

I know this is not super efficient, but I do not believe there is a single call to achieve a image of a specific size.