Compress UIImage to a specific size in megabytes

In obj- how to get the size of a specific UIImage stored in a custom NSMutableArray ? This is the first thing I want to do. Secondly, knowing that the image is larger in file size (say 15 MB) than my own file size size (say 5 MB), how do I make image compression closest to the file size limit, say 4.99 MB?

+4
source share
1 answer

I saw this on another question about stacj overflow link - compress image by size - iPhone SDK

but I still combine the two answers, I also used this code for 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 this is to reload the file in a loop until you find the size you want. First you can find the height and width and guess the compression ratio (more compression of the image), after you compress it, check the size and split the difference again.

I know that this is not very effective, but I do not believe that there is one call to achieve an image of a certain size.

+12
source

All Articles