views:

50

answers:

2
+3  Q: 

size of an image

From times to times I have to know the width and height of images. I am using the following code:

UIImage *imageU = [UIImage imageWithContentsOfFile:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"myImage.png"]];

CGFloat imageW = CGImageGetWidth(imageU.CGImage);
CGFloat imageH = CGImageGetHeight(imageU.CGImage);

My question is that if it is there any other way to know the width and height of an image, in pixels, without having to load the image on a variable, that's probably consuming memory. Can the dimensions be read from the file directly without loading the whole image?

This has to work for PNG and JPEG.

thanks.

+1  A: 

You can parse the PNG file which contain the size info in the header. See http://stackoverflow.com/questions/1551300/get-size-of-image-without-loading-in-to-memory.

(BTW, you can use imageU.size to get a CGSize of the image.)

KennyTM
A: 

I don't think you can do this "for free", speaking in terms of memory use. You could create an NSInputStream and read/parse the data of the IHDR section (follow @KennyTM's link), then discard everything.

jtrim