Get the correct image width and height of an NSImage

后端 未结 5 2012
北荒
北荒 2021-02-04 02:20

I use the code below to get the width and height of a NSImage:

NSImage *image = [[[NSImage alloc] initWithContentsOfFile:[NSString stringWithFormat:s]] autorelea         


        
相关标签:
5条回答
  • 2021-02-04 02:24

    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
    
    0 讨论(0)
  • 2021-02-04 02:27

    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);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-04 02:40

    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.

    0 讨论(0)
  • 2021-02-04 02:46

    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.

    0 讨论(0)
提交回复
热议问题