CGBitmapContextCreate : unsupported parameter combination

Arnaud picture Arnaud · Aug 5, 2013 · Viewed 7.6k times · Source

I am trying to create a 8-bit grayscale context as follows :

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate(
    data, m_width, m_height, 8, m_width, colorSpace, 
    kCGBitmapByteOrder32Little|kCGImageAlphaNone);

But I have the following error :

CGBitmapContextCreate: unsupported parameter combination: 
8 integer bits/component; 8 bits/pixel; 1-component color space; 
kCGImageAlphaNone; 1936 bytes/row.

Why is this combination unsupported ?

Answer

danielv picture danielv · Oct 13, 2013

The supported Bits per Component, Bits per Pixel, color space combinations can be found in "Quartz 2D Programming Guide"

As Nikolai wrote, using kCGBitmapByteOrder32Little with kCGImageAlphaNone doesn't make sense for gray color space (and not supported).

Now depending on your bytes per row and height, you need to provide enough allocated memory to CGBitmapContextCreate in you data parameter. You didn't show the code where you set the height and allocated the memory for data, but I guess your problem is there.

Also, you don't actually need to allocate the memory yourself (as of iOS 4.0), according to CGBitmapContextCreate documentation, you can pass NULL as the data to have the memory allocated for you. You can still access the data pointer later by requesting it with CGBitmapContextGetData.

Another note is that passing m_width as bytesPerRow is only correct in this case (gray color space with 1 byte per pixel) but probably is not good practice. If you pass NULL for data, you can also pass 0 here to have it calculated for you automatically.