gpt4 book ai didi

ios - 更快地裁剪图像

转载 作者:行者123 更新时间:2023-11-28 18:37:20 24 4
gpt4 key购买 nike

我正在尝试在 iOS 中裁剪我的图像一段时间。我的代码运行良好但速度不够快。当我向它提供大约 20-25 张图像时,处理它需要 7-10 秒。我已经尝试了所有可能的方法来解决这个问题,但没有成功。我不确定我错过了什么。

- (UIImage *)squareImageWithImage:(UIImage *)image scaledToSize:(CGSize)targetSize {

UIImage *sourceImage = image;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;
CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (CGSizeEqualToSize(imageSize, targetSize) == NO)
{
CGFloat widthFactor = targetWidth / width;
CGFloat heightFactor = targetHeight / height;

if (widthFactor > heightFactor)
{
scaleFactor = widthFactor; // scale to fit height
}
else
{
scaleFactor = heightFactor; // scale to fit width
}

scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;

// center the image
if (widthFactor > heightFactor)
{
thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
}
else
{
if (widthFactor < heightFactor)
{
thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
}
}
}

UIGraphicsBeginImageContext(targetSize); // this will crop

CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage = UIGraphicsGetImageFromCurrentImageContext();

if(newImage == nil)
{
NSLog(@"could not scale image");
}

//pop the context to get back to the default
UIGraphicsEndImageContext();

return newImage;
}

最佳答案

您最初的问题没有正确说明问题,现在确实如此:这些操作花费这么长时间的原因是缩放图像所需的 CPU 周期数(而不是裁剪图像,这更简单、更快)。缩放时,系统需要对某个区域周围的一些像素进行混合,这会消耗大量 CPU 周期。您可以通过组合使用多种技术来加快速度,但没有单一的答案。

1) 使用 block 并在并发调度队列上调度这些图像操作,以获得并行性。我相信最新的 iPad 有 4 个核心,您可以这样使用。 [UIGraphicsBeginImageContext 是线程安全的]。

2)获取ContextRef指针,将插值设置设为最低:

UIGraphicsBeginImageContext(targetSize);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetInterpolationQuality(context, kCGInterpolationLow);
...

3) 作弊 - 除非是二的幂,否则不要缩放。在这种技术中,您将确定两个的“最佳”幂来缩小图像,扩展宽度和高度以适合您的目标尺寸。如果可以使用 2 的幂,则可以使用 UIImage 中的 CGImageRef,获取像素指针,每隔一个像素/每隔一行复制一个,然后真正快速地创建一个较小的图像(使用 CGImageCreate)。它可能不如让系统缩放图像时获得的质量高,但速度会更快。这显然是相当多的代码,但您可以通过这种方式使操作变得非常快。

4) 重新定义你的任务。与其尝试调整一组图像的大小,不如更改您的应用程序,以便您一次只显示一两个调整大小的图像,并在用户查看它们时,在后台队列中执行其他图像操作。这是为了完整起见,我想您已经想到了这一点。

PS:如果这对你有用,不需要赏金,而是帮助别人。

关于ios - 更快地裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16389175/

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