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?
Asked
Active
Viewed 7,686 times
7

Sergey Grischyov
- 11,995
- 20
- 81
- 120
-
1Compression algorithms cannot be written to compress every file to a specific size, and estimates by any compression framework may be astronomically incorrect depending on the parameters given. The only accurate way to check would be to compress first and ask questions later. File size is an [attribute](https://developer.apple.com/library/ios/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html#//apple_ref/doc/constant_group/File_Attribute_Keys) you can get easily. – CodaFi Sep 19 '13 at 15:37
-
You can check the size of the UIImage by it's `NSData` representation and an instance method of `NSData` class `-[NSData length]`. https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html#//apple_ref/occ/instm/NSData/length. – art-divin Sep 19 '13 at 15:54
1 Answers
16
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.

Community
- 1
- 1

kshitij godara
- 1,523
- 18
- 30