Search code examples
swiftmacoscocoansimage

NSImage doesn't work with all images


I'm loading images using NSImage class in my application like that.

 if let image = NSImage(contentsOfURL: openPanel.URL!) {
  ...
 }

It works fine with most of images. I then convert it to CGImage and use like I want. But with some images it simply glitches and I cant understand why. For example If I load image size 2133x2133, it appears like nothing and if I'm printing image.size I see very strange (511.92, 511.92).

What can cause that type of behaviour? All images are in PNG format. At the same time, I can load image with size (2048.0, 1536.0) and everything works just fine.

How one should even start debugging loading with NSImage?

This is the example of an image:

http://rgho.st/6CVKMR2ZM/image.png

When I create CGImage from that using this func, I see nothing:

    var imageRect = CGRectMake(0, 0, newImage.size.width, newImage.size.height)
    let imageRef = newImage.CGImageForProposedRect(&imageRect, context: nil, hints: nil)

Solution

  • Here is my solution: use real image size, not the one Apple calculates for me using DPI.

        var w = 0
        var h = 0
        for r in newImage.representations {
            w = max(w, r.pixelsWide)
            h = max(h, r.pixelsHigh)
        }
        var imageRect = CGRectMake(0, 0, CGFloat(w), CGFloat(h))
        let imageRef = newImage.CGImageForProposedRect(&imageRect, context: nil, hints: nil)