Resize UIImage
with custom size
by checking actual image ratio for reducing image size. I have already tried this UIImageJPEGRepresentation(Image, 0.8);
but problem with this is that image quality is reducing. Any help would be really appreciated. Thank you
Pass UIImage
to below method which resize your image with custom height/width and you can also give compression value of image for reducing image size and Check image size before and after resizing.
Here is sample method-
-(UIImage *)resizeImage:(UIImage *)image
{
NSInteger imageActualSize = UIImageJPEGRepresentation(image,1).length;
NSLog(@"size of IMAGE before resizing: %@ ", [NSByteCountFormatter stringFromByteCount:imageActualSize countStyle:NSByteCountFormatterCountStyleFile]);
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = 400.0; // your custom height
float maxWidth = 350; // your custom width
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();
NSInteger imageReduceSize = imageData.length;
NSLog(@"size of IMAGE after resizing: %@ ",[NSByteCountFormatter stringFromByteCount:imageReduceSize countStyle:NSByteCountFormatterCountStyleFile]);
return [UIImage imageWithData:imageData];
}
This will help you..:)
+ (UIImage *)resizeImage:(UIImage *)image toSize:(CGSize)newSize {
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
very easy way to do this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.