6

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 ?

Arnaud
  • 7,259
  • 10
  • 50
  • 71

2 Answers2

8

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.

danielv
  • 3,039
  • 25
  • 40
  • 1
    +1 for the awesome tip - "If you pass NULL for data, you can also pass 0 here to have it calculated for you automatically." It works but I couldn't find a reference to it in the docs tho, do you have one? – Robert Jun 09 '14 at 15:09
  • It's right there in the documentation for CGBitmapContextCreate function, look at the description of the bytesPerRow parameter. – danielv Jun 10 '14 at 11:28
  • Yep - I don't know how I missed that! – Robert Jun 10 '14 at 13:07
2

It's probably the kCGBitmapByteOrder32Little (which makes no sense for single channel gray scale images any way).

You can just drop that from the pixel format specification.

Nikolai Ruhe
  • 81,520
  • 17
  • 180
  • 200
  • Thanks for your answer. I have done as you described, but the error now changed to : `CGBitmapContextCreate: invalid data bytes/row: should be at least 7744 for 8 integer bits/component, 3 components, kCGImageAlphaNoneSkipLast.` – Arnaud Aug 06 '13 at 02:49