Instead of answering your question directly, I'll show you what I think is a better way: use the ImageIO framework.
#import <ImageIO/ImageIO.h>
Here's how to load a reduced size version of an image from disk (imageSource
is an NSURL; scale
, maxw
, and maxh
must be set beforehand to the scale and maximum dimensions you want):
CGImageSourceRef src =
CGImageSourceCreateWithURL((__bridge CFURLRef)imageSource, nil);
NSDictionary* d = @{
(id)kCGImageSourceShouldAllowFloat: (id)kCFBooleanTrue,
(id)kCGImageSourceCreateThumbnailWithTransform: (id)kCFBooleanTrue,
(id)kCGImageSourceCreateThumbnailFromImageAlways: (id)kCFBooleanTrue,
(id)kCGImageSourceThumbnailMaxPixelSize: @((int)(maxw > maxh ? maxw : maxh))
};
CGImageRef imref =
CGImageSourceCreateThumbnailAtIndex(src, 0, (__bridge CFDictionaryRef)d);
if (NULL != src)
CFRelease(src);
UIImage* im =
[UIImage imageWithCGImage:imref scale:scale orientation:UIImageOrientationUp];
if (NULL != imref)
CFRelease(imref);
The great thing about this code is that we never hold the large version of the image in memory; it is never loaded. We end up with a smaller UIImage and we are ready to use it in our interface.
If what you have is NSData from the Internet and you have not saved it to disk, then to create your image source, use this:
src = CGImageSourceCreateWithData((__bridge CFDataRef)imageSource, nil);
But really, if the images are big, you should be using a download task so that the whole image is never in memory, but is saved to disk as it arrives.