在iPhone上高效创建缩略图

5

在iPhone上从任意网络图片创建缩略图的最有效方式是什么?


1
截至2014年,ImageIO仍然是最快的。有关其他技术的良好摘要,请参阅此文章:http://nshipster.com/image-resizing/。 - Chris Conover
3个回答

8
比较两种从图像快速创建缩略图的方法,请查看以下链接以获取详细信息:http://www.cocoaintheshell.com/2011/01/uiimage-scaling-imageio/http://vocaro.com/trevor/blog/2009/10/12/resize-a-uiimage-the-right-way/
将来,只需从第一个链接中复制粘贴代码即可。
第一种方法是使用UIKit。
void)buildGallery
{
    for (NSUInteger i = 0; i < kMaxPictures; i++)
    {
        NSInteger imgTag = i + 1;
        NYXPictureView* v = [[NYXPictureView alloc] initWithFrame:(CGRect){.origin.x = x, .origin.y = y, .size = _thumbSize}];
        NSString* imgPath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d", imgTag] ofType:@"jpg"];
        UIImage* fullImage = [[UIImage alloc] initWithContentsOfFile:imgPath];
        [v setImage:[fullImage imageScaledToFitSize:_thumbSize]];
        [fullImage release];
}

进行基准测试后,我得到以下结果:

  • 时间分析器:4233毫秒
  • 实时字节数:695千字节
  • 总使用字节数:78.96兆字节

第二种方法,使用ImageIO

-(void)buildGallery
{
    for (NSUInteger i = 0; i < kMaxPictures; i++)
    {
        NSInteger imgTag = i + 1;
        NYXPictureView* v = [[NYXPictureView alloc] initWithFrame:(CGRect){.origin.x = x, .origin.y = y, .size = _thumbSize}];
        NSString* imgPath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%d", imgTag] ofType:@"jpg"];
        CGImageSourceRef src = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:imgPath], NULL);
        CFDictionaryRef options = (CFDictionaryRef)[[NSDictionary alloc] initWithObjectsAndKeys:(id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform, (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageIfAbsent, (id)[NSNumber numberWithDouble:_maxSize], (id)kCGImageSourceThumbnailMaxPixelSize, nil];
        CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options); // Create scaled image
        CFRelease(options);
        CFRelease(src);
        UIImage* img = [[UIImage alloc] initWithCGImage:thumbnail];
        [v setImage:img];
        [img release];
        CGImageRelease(thumbnail);
    }

他们给了我这个数据:

  • 时间分析器:3433毫秒
  • 实时内存使用量:681千字节
  • 总内存使用量:77.63兆字节

可以看出,使用ImageIO比UIKit快约19%,并且内存使用略低。


2

第一次尝试时,给了我“CGBitmapContextCreate: unsupported colorspace.”的错误。检查了评论后发现该库的范围非常有限。除了它们是PNG或JPEG格式外,我不能假设图像的其他内容。 - hpique
这是由于API对位分辨率、alpha和色彩空间之间的关系非常挑剔所导致的。您必须检查图像是否具有正确的配置,如果没有,则必须创建一个新的、格式正确的图像。这是真的无法避免的。我认为没有人做过适用于所有情况的通用调整大小。 - TechZen
如果配置正确,我该如何检查并创建格式正确的图像?如果配置不正确,我该如何创建格式正确的图像? - hpique

-3
到目前为止,我发现在任何图像上运作的唯一方法是将其显示在具有正确大小的ImageView中,然后从该视图创建位图。
虽然远非高效。

关于作者的尊重,这不应该被标记为正确答案。 - Chris Conover

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接