Accessing Image Properties Without Loading the Image Into Memory

Sometimes you might want to retrieve certain properties from an image file, such as the image’s dimensions or other metadata, without actually displaying the full-size image on screen. The simplest way to do that on iOS is using the UIImage class:

The problem with this approach is that the entire image gets loaded into memory. And since the pixel data is stored uncompressed in memory, even a small 512 × 512 image (that fills less than half of an iPhone 4’s screen) will take up 1 MB of memory.

CGImageSource

As of iOS 4, the SDK includes a better solution in the form of the CGImageSource... set of functions, which have been available on the Mac since forever. These functions allow you to access certain image metadata without having to load the actual pixel data into memory. For example, getting the pixel dimensions works like this (make sure to include the ImageIO.framework in your target):

All the Metadata You Dreamed Of

The dictionary returned by CGImageSourceCopyPropertiesAtIndex() contains a lot more than just the image dimensions. If present, it includes the complete EXIF and IPTC metadata and also various file-format-specific information for TIFF, GIF, JPEG, PNG and Raw files (among others).

As an example, let’s read out the date a photo was taken, the model name of the camera and the GPS coordinates stored in the metadata:

An NSLog(@"Image properties: %@", (NSDictionary *)imageProperties); will quickly show you all the available metadata for a particular image. It’s fun to experiment with different files. The documentation lists all available metadata keys at CGImageProperties Reference.