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.
This breaks down when you reach a compression size of 0.0 and the image is still bigger than your maximum size.
ReplyDeletePretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
ReplyDeleteMobile App Development Company
Android app Development Company
ios app development Company
Mobile App Development Companies
ReplyDeleteProfessional Certification training for HIPAA security officer training and HIPAA privacy officer training for $1200-$3200. Classroom, online, onsite and online live. Get certified today.