Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

image compression by size - iPhone SDK

I would like to compress images (camera/photo library) and then send it to the server. I know I can compress by height and width, 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 I achieve this (compress to a fixed size) without using any third party library? Thanks for any help.

like image 650
DonDyck Avatar asked Feb 29 '12 21:02

DonDyck


1 Answers

Heres some 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

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); } 
like image 121
kgutteridge Avatar answered Sep 20 '22 18:09

kgutteridge