gpt4 book ai didi

ios - 如何按数据大小缩小 IOS 中的 UIImage

转载 作者:IT王子 更新时间:2023-10-29 08:11:24 27 4
gpt4 key购买 nike

我希望在 iOS 中缩小 UIImage

我在下面看到了其他问题以及他们关于如何按尺寸缩小图像的方法。 Resizing Images Objective-C
How to resize the image programmatically in objective-c in iphone
The simplest way to resize an UIImage?

这些问题都是基于将图像调整为特定大小。在我的例子中,我希望根据最大尺寸重新调整/缩小图像。

例如,我想将最大 NSData 大小设置为 500 KB。我知道我可以这样获取图像的大小://检查返回图像的大小

NSData *imageData = UIImageJPEGRepresentation(image, 0.5);

// Log out the image size
NSLog(@"%lu KB",(imageData.length/1024));

我想在这里做某种形式的循环。如果尺寸大于我设置的最大尺寸,我想稍微缩小图像,然后检查尺寸。如果尺寸仍然太大,请再次稍微缩小,然后再次检查,直到它低于最大设置尺寸。

我不确定最好的方法是什么。理想情况下,我不想一直将图像缩小到特定大小,而只是每次都稍微缩小图像。这样我就可以拥有图像本身的最大(w/h 大小)及其最大大小(字节)。如果我一次只略微缩减规模,实现这一目标的最佳方法是什么?

编辑为了确认,我希望重新调整实际图像的大小,但要重新调整图像的大小,使其小于最大 NSData 长度。例如:
-检查NSData长度
-如果高于最大值,我想将 UIImage 传递给方法
- 然后循环执行此方法,每次都稍微调整实际图像大小
- 直到小于最大NSData长度,然后返回图像?

最佳答案

现在,您有一个例程:

// Check if the image size is too large
if ((imageData.length/1024) >= 1024) {

while ((imageData.length/1024) >= 1024) {
NSLog(@"While start - The imagedata size is currently: %f KB",roundf((imageData.length/1024)));

// While the imageData is too large scale down the image

// Get the current image size
CGSize currentSize = CGSizeMake(image.size.width, image.size.height);

// Resize the image
image = [image resizedImage:CGSizeMake(roundf(((currentSize.width/100)*80)), roundf(((currentSize.height/100)*80))) interpolationQuality:kMESImageQuality];

// Pass the NSData out again
imageData = UIImageJPEGRepresentation(image, kMESImageQuality);

}
}

我不建议递归地调整图像大小。每次调整大小时,都会损失一些质量(通常表现为图像“软化”,细节丢失,具有累积效果)。您总是想返回原始图像并将其调整得越来越小。 (顺便说一句,if 语句也是多余的。)

我可能会提出以下建议:

NSData  *imageData    = UIImageJPEGRepresentation(image, kMESImageQuality);
double factor = 1.0;
double adjustment = 1.0 / sqrt(2.0); // or use 0.8 or whatever you want
CGSize size = image.size;
CGSize currentSize = size;
UIImage *currentImage = image;

while (imageData.length >= (1024 * 1024))
{
factor *= adjustment;
currentSize = CGSizeMake(roundf(size.width * factor), roundf(size.height * factor));
currentImage = [image resizedImage:currentSize interpolationQuality:kMESImageQuality];
imageData = UIImageJPEGRepresentation(currentImage, kMESImageQuality);
}

请注意,我没有触及原始图像 image,而是通过每次从原始图像调整大小来分配 currentImage,每次缩小比例时间。

顺便说一句,如果你想知道我的神秘 1.0/sqrt(2.0),我试图在你的迭代 80% 因子和我希望通过2 在我能做到的地方(因为当以 2 的幂完成时,减少会保留更多的锐度)。但是使用任何你想要的 adjustment 因素。

最后,如果您在大图像上执行此操作,您可能会考虑使用 @autoreleasepool block 。您需要在 Instruments 的 Allocations 中分析您的应用程序,并查看您的高水位线在哪里,因为在没有自动释放池的情况下,这可能会构成相当激进的内存使用。

关于ios - 如何按数据大小缩小 IOS 中的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20403805/

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