Forked from akshay1188/whatsapp-image-compression
Last active
August 29, 2015 14:07
-
-
Save doppelganger9/e3697b66be3b53936242 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).