Last active
June 10, 2023 16:42
-
-
Save akshay1188/4749253 to your computer and use it in GitHub Desktop.
Whatsapp like image compression
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
- (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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@knox kUTTypeJPEG deprecated