Skip to content

Instantly share code, notes, and snippets.

@akshay1188
Last active June 10, 2023 16:42
Show Gist options
  • Save akshay1188/4749253 to your computer and use it in GitHub Desktop.
Save akshay1188/4749253 to your computer and use it in GitHub Desktop.
Whatsapp like image compression
- (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.5;//50 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);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];
}
@YogeshPateliOS
Copy link

@knox kUTTypeJPEG deprecated

@MounikaMadishetti
Copy link

@YogeshPateliOS We can use UTType. jpeg.identifier

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