gpt4 book ai didi

IOS如何根据实际图像比例调整图像大小并提供自定义尺寸?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:06:51 26 4
gpt4 key购买 nike

通过检查实际图像比例以减小图像尺寸,使用自定义尺寸调整UIImage。我已经尝试过这个 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];

}

这会帮助你..:)

关于IOS如何根据实际图像比例调整图像大小并提供自定义尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36998350/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com