I use the code below to get the width and height of a NSImage:
NSImage *image = [[[NSImage alloc] initWithContentsOfFile:[NSString stringWithFormat:s]] autorelea
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