Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save doppelganger9/e3697b66be3b53936242 to your computer and use it in GitHub Desktop.
Save doppelganger9/e3697b66be3b53936242 to your computer and use it in GitHub Desktop.
#define MAXIMUM_IMAGE_WEIGHT 1024*1024
- (UIImage *)compressImage:(UIImage *)image {
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = 600.0;
float maxWidth = 800.0;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.8;//80 percent compression
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if(imgRatio < maxRatio){
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio){
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}else{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
// iteratively lowers compression quality to obtain an acceptable image weight.
while (imageData.length >= MAXIMUM_IMAGE_WEIGHT && compressionQuality > 0)
{
compressionQuality -= 0.05;
imageData = UIImageJPEGRepresentation(img, compressionQuality);
}
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];
}
@doppelganger9
Copy link
Author

I needed to replace line 32 with the following iterative compression to limit the image weight with the MAXIMUM_IMAGE_WEIGHT constant.
Hence I'll have two factor limit : size (pixels) and weight (kilobytes).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment