Swift 4.1 Failed to get a bitmap representation of this NSImage
Asked Answered
B

1

6

This code sample was working in a macOS playground:

import Cocoa

import XCPlayground

func getResImg(name: String, ext: String) -> CIImage {
   guard let fileURL = Bundle.main.url(forResource: name, withExtension: ext) else {
    fatalError("can't find image")
   }
   guard let img = CIImage(contentsOf: fileURL) else {
    fatalError("can't load image")
   }
   return img

}

var img = getResImg(name: "noise", ext: "jpg")

After upgrading to Swift 4.1 it doesn't. Error: Failed to get a bitmap representation of this NSImage.

How does it work now in Swift 4.1?

Birchard answered 6/6, 2018 at 14:29 Comment(3)
Just ran into the same issue. Did you ever find a solution?Darcydarda
Just tried it out with the latest Xcode but still not workingBirchard
It's definitely a Playground issue. I've moved the same code into a macOS project and everything works fine now.Darcydarda
S
6

I ran into the same issue even though I was using a macOS project and wasn't able to pinpoint what's going wrong here, but I found a workaround which fixes playground rendering for CIImage by using a CustomPlaygroundDisplayConvertible

Just add the following code to the top of your playground and your images will render again

extension CIImage: CustomPlaygroundDisplayConvertible {
    static let playgroundRenderContext = CIContext()
    public var playgroundDescription: Any {
        let jpgData = CIImage.playgroundRenderContext.jpegRepresentation(of: self, colorSpace: CGColorSpace(name: CGColorSpace.sRGB)!, options: [:])!
        return NSImage(data: jpgData)!
    }
}
Silin answered 5/1, 2019 at 14:1 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.