Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compress UIImage to certain size in megabytes [duplicate]

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?

like image 852
Sergey Grischyov Avatar asked Sep 19 '13 15:09

Sergey Grischyov


1 Answers

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.

like image 101
kshitij godara Avatar answered Oct 18 '22 14:10

kshitij godara