Get the correct image width and height of an NSImage

arachide picture arachide · Aug 9, 2012 · Viewed 14.7k times · Source

I use the code below to get the width and height of a NSImage:

NSImage *image = [[[NSImage alloc] initWithContentsOfFile:[NSString stringWithFormat:s]] autorelease];
imageWidth=[image size].width;
imageHeight=[image size].height;
NSLog(@"%f:%f",imageWidth,imageHeight);

But sometime imageWidth, imageHeight does not return the correct value. For example when I read an image, the EXIF info displays:

PixelXDimension = 2272;
PixelYDimension = 1704;

But imageWidth, imageHeight outputs

521:390 

Answer

Kibernetik picture Kibernetik · Nov 5, 2012

Dimensions of your image in pixels is stored in NSImageRep of your image. If your file contains only one image, it will be like this:

NSImageRep *rep = [[image representations] objectAtIndex:0];
NSSize imageSize = NSMakeSize(rep.pixelsWide, rep.pixelsHigh);

where image is your NSImage and imageSize is your image size in pixels.