Get the correct image width and height of an NSImage

Viewed 16140

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 
6 Answers

SWIFT 4

You have to make a NSBitmapImageRep representation of the NSImage to get the correct pixel height and width. First a this extension to gather a CGImage from the NSImage:

extension NSImage {
    @objc var CGImage: CGImage? {
        get {
            guard let imageData = self.tiffRepresentation else { return nil }
            guard let sourceData = CGImageSourceCreateWithData(imageData as CFData, nil) else { return nil }
            return CGImageSourceCreateImageAtIndex(sourceData, 0, nil)
        }
    }
}

Then when you want to get the height and width:

let rep = NSBitmapImageRep(cgImage: (NSImage(named: "Your Image Name")?.CGImage)!)
let imageHeight = rep.size.height
let imageWidth = rep.size.width

i make a extension like this:

extension NSImage{
    var pixelSize: NSSize?{
        if let rep = self.representations.first{
            let size = NSSize(width: rep.pixelsWide, height: rep.pixelsHigh)
            return size
        }
        return nil
    }
}
Related