调整大小UIImage
与custom size
通过检查实际的图像比用于降低图像的大小。我已经尝试过了,UIImageJPEGRepresentation(Image, 0.8);
但是问题是图像质量下降了。任何帮助将非常感激。谢谢
传递UIImage
到下面的方法,该方法可以使用自定义的高度/宽度来调整图像的大小,还可以提供图像的压缩值以减小图像大小,并在调整大小之前和之后检查图像大小。
这是示例方法-
-(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];
}
这将帮助您.. :)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句