As you know the iPhone guidelines discourage loading UIImage
s that are greater than 1024x1024.
The size of the images that I would have to load varies, and I would like to check the size of the image I am about to load; however using the .size
property of UIImage
requires the image to be loaded... which is exactly what I am trying to avoid.
Is there something wrong in my reasoning or is there a solution?
As of iOS 4.0, the iOS SDK includes the CGImageSource...
functions (in the ImageIO framework). It's a very flexible API to query metadata without loading the image into memory. Getting the pixel dimensions of an image should work like this (make sure to include the ImageIO.framework in your target):
#import <ImageIO/ImageIO.h>
NSURL *imageFileURL = [NSURL fileURLWithPath:...];
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);
if (imageSource == NULL) {
// Error loading image
...
return;
}
CGFloat width = 0.0f, height = 0.0f;
CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
CFRelease(imageSource);
if (imageProperties != NULL) {
CFNumberRef widthNum = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
if (widthNum != NULL) {
CFNumberGetValue(widthNum, kCFNumberCGFloatType, &width);
}
CFNumberRef heightNum = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
if (heightNum != NULL) {
CFNumberGetValue(heightNum, kCFNumberCGFloatType, &height);
}
// Check orientation and flip size if required
CFNumberRef orientationNum = CFDictionaryGetValue(imageProperties, kCGImagePropertyOrientation);
if (orientationNum != NULL) {
int orientation;
CFNumberGetValue(orientationNum, kCFNumberIntType, &orientation);
if (orientation > 4) {
CGFloat temp = width;
width = height;
height = temp;
}
}
CFRelease(imageProperties);
}
NSLog(@"Image dimensions: %.0f x %.0f px", width, height);
(adapted from "Programming with Quartz" by Gelphman and Laden, listing 9.5, page 228)