Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4.1 Failed to get a bitmap representation of this NSImage

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?

like image 422
Fritz Avatar asked Jun 06 '18 14:06

Fritz


1 Answers

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)!
    }
}
like image 62
heilerich Avatar answered Sep 22 '22 18:09

heilerich