Get the correct image width and height of an NSImage

坚强是说给别人听的谎言 提交于 2019-12-03 08:42:44

问题


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 

回答1:


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.




回答2:


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




回答3:


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.




回答4:


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);



回答5:


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


来源:https://stackoverflow.com/questions/11876963/get-the-correct-image-width-and-height-of-an-nsimage

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