Get the correct image width and height of an NSImage

后端 未结 5 2024
北荒
北荒 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条回答
  •  猫巷女王i
    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
    

提交回复
热议问题