Search code examples
objective-cmacoscocoansimage

Get the correct image width and height of an NSImage


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 

Solution

  • 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.