Get pixels and colours from NSImage

Nippysaurus picture Nippysaurus · Jan 3, 2010 · Viewed 11.6k times · Source

I have created an NSImage object, and ideally would like to determine how many of each pixels colour it contains. Is this possible?

Answer

Peter Hosey picture Peter Hosey · Jan 3, 2010

I suggest creating your own bitmap context, wrapping it in a graphics context and setting that as the current context, telling the image to draw itself, and then accessing the pixel data behind the bitmap context directly.

This will be more code, but will save you both a trip through a TIFF representation and the creation of thousands or millions of NSColor objects. If you're working with images of any appreciable size, these expenses will add up quickly.