resizing a UIImage without loading it entirely into memory?

前端 未结 2 1659
长情又很酷
长情又很酷 2020-11-28 23:10

I\'m developing an application where a user could potentially try and load very very large images. These images are first displayed as thumbnails in a table view. My origina

2条回答
  •  天命终不由人
    2020-11-29 00:14

    You should take a look at CGImageSource in ImageIO.framework, but it is only available since iOS 4.0.

    Quick example :

    -(UIImage*)resizeImageToMaxSize:(CGFloat)max path:(NSString*)path
    {
        CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], NULL);
        if (!imageSource)
            return nil;
    
        CFDictionaryRef options = (CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:
            (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailWithTransform,
            (id)kCFBooleanTrue, (id)kCGImageSourceCreateThumbnailFromImageIfAbsent,
            (id)@(max),
            (id)kCGImageSourceThumbnailMaxPixelSize,
            nil];
        CGImageRef imgRef = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options);
    
        UIImage* scaled = [UIImage imageWithCGImage:imgRef];
    
        CGImageRelease(imgRef);
        CFRelease(imageSource);
    
        return scaled;
    }
    

提交回复
热议问题