Getting Rid of kCGImageSourceTypeIdentifierHint Error when Loading NSImage from a File

This post is mostly for people googling for a similar error message as I did, being stuck clueless.

Here it is, a message in the Xcode log that you can get when you load an NSImage:

extractOptions:147: *** unknown hint identifier ‘kCGImageSourceTypeIdentifierHint:dyn.age80q2pssvu1g8pftb4gn5xxrf106’ – ignoring…

The source of the problem, for me, was loading an image via NSImage.init(contentsOf:) where the URL had a custom file extension. Say you store a PNG image with the .fantasyextension path extension, the message above is what you may get. The dictionary value is prefixed with dyn.age80, followed by a hash of some sort. The hash changes depending on the file extension. For .attachment, I got "dyn.age80c7dyqfv0u5pfr34a", for example.

It’s okay to load a PNG file from a wrong extension, e.g. .jpeg; you won’t get the error there.

My best guess is that path extensions that no app has registered will produce this message. I wasn’t better off without a file extension, either, though. For example "dyn.age8u" is the value I get when the file name is the number 2428272662287976958 (which is the hashValue of the file name I used before to try what happens then).

Apparently, kCGImageSourceTypeIdentifierHint is a CoreGraphics (because of the kCG prefix) image-loading hint that is automatically provided based on the path extension when you try to load an NSImage from a URL where the file extension is not something image-y.

Update 2023-04-19: Checking out the convenience initializer NSImage.init?(byReferencingFile:) provides a hint in its documentation that the file extension (actually ‘path extension’ elsewhere in Foundation) is matched with registered types:

The filename parameter should include the file extension that identifies the type of the image data. The mechanism that actually creates the image representation for filename looks for an NSImageRep subclass that handles that data type from among those registered with NSImage.

I don’t know if there’s a way to get rid of this hint when loading, and I don’t want to create a CoreGraphics image source myself. I bypass the convenience hint provision completely, instead.

Here’s a quick fix for you:

func image(fromURL url: URL) -> NSImage? {
    guard let data = try? Data(contentsOf: url) else { return nil }
    guard let image = NSImage(data: data) else { return nil }
    return image
}

The path extension-based “type identifier” hint is a useful feature. But if you know that you expect a properly encoded image, reading in a hint-less piece of Data works just as well.

So don’t worry if you see this error. The file may be totally fine. It’s just that AppKit cannot use the misleading file extension information for anything.