Sunday, June 3, 2012

image compression by size by maintaining original height and width

While we develop application for iphone we face 
a serious problem of memory because we use images 
of large size, for better quality, but some time 
it is required to compress images (from MB to KB) 
but without change in height and width 
for sending it to server or other purpose.
 
There is code in SDK to compress image by height 
and width but but I would like to compress the images 
by size to a fixed size (200 KB) only and keep the 
original height and width. The scale factor in 
JPEGRepresentation does not represent the size and 
only compression quality. 
 
How can we achieve this (compress to a fixed size) 
without using any third party library?
 

example code that will attempt to compress an image 
for you so that it doesn't exceed either a max 
compression or maximum file size.
 

UIImage *existingImage=[UIImage imageNamed:
@"ExistingImg.jpg"];

CGFloat compression = 0.9f;
CGFloat maxCompression = 0.1f;
 
int maxFileSize = existingImage.size.height*
existingImage.size.width;
 
NSData *imageData = UIImageJPEGRepresentation(existingImage,
 compression);
 
while ([imageData length] > maxFileSize && 
compression > maxCompression)
{
    compression -= 0.1;
    imageData = UIImageJPEGRepresentation(existingImage, 
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.