Get the correct image width and height of an NSImage

自作多情 提交于 2019-12-03 00:13:28

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.

Paresh Navadiya

NSImage size method returns size information that is screen resolution dependent. To get the size represented in the actual file image you need to use an NSImageRep.

Refer nsimage-size-not-real-size-with-some-pictures link and get helped

Apple uses a point system based on DPI to map points to physical device pixels. It doesnt matter what the EXIF says, it matters how many logical screen points your canvas has to display the image.

iOS and OSX perform this mapping for you. The only size you should be concerned about is the size returned from UIImage.size

You cant (read shouldnt have to shouldnt care) do the mapping to device pixels yourself, thats why apple does it.

the direct API gives also the correct results

CGImageRef cgImage = [oldImage CGImageForProposedRect:nil context:context hints:nil];
size_t width = CGImageGetWidth(cgImage);
size_t height = CGImageGetHeight(cgImage);

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!