kCGErrorInvalidConnection - 1002
The parameter representing a connection to the window server is invalid.
It looks like the Cocoa aspects of your application don't have a
proper connection to the window server. NSImage uses the window
server to create a target graphic context when you attempt to draw
into it.
Have you tried adding in a call to [NSApplication sharedApplication]
someplace in your application initialization? This kicks AppKit to
bootstrap itself.