12

Under what circumstances will a CGBitmapContext fail to allocate? I have a table view, and it has multiple view options. The user can see a small table cell with just previews, one larger preview per line, or two side by side previews per line. The first two render just fine, but the third one fails. There are no error messages from CGBitmapContextCreate, just errors after when I try to use it (i.e. invalid context 0x0).

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
//size is a passed parameter
CGContextRef c = CGBitmapContextCreate(NULL, size.width, size.height, 8, size.width*4, colorSpace, kCGImageAlphaNoneSkipLast);
CGColorSpaceRelease(colorSpace);

I am targeting iOS 5.0, building with 5.1. The only difference between the working and non-working version is that the non-working version attempts to do it twice (size is small, less than 100x100). Only the right side has this problem (i.e. the second attempt). The first attempt still works.

borrrden
  • 33,256
  • 8
  • 74
  • 109

2 Answers2

14

This can happen if size.width and/or size.height is 0. Put a NSLog to check the sizes every time you call this method to see if that's the case.

graver
  • 15,183
  • 4
  • 46
  • 62
  • 1
    Ah, excellent. I thought I checked those, but apparently not well enough. Some of them were, in fact, 0. Well done, thanks!! – borrrden Jun 05 '12 at 10:07
6

For posterity, this can also happen if you specify a 'bytesPerRow' that is not large enough to accommodate specified width.

Using Apple's sample code from https://developer.apple.com/library/ios/qa/qa1702/_index.html

I noticed that CVPixelBufferGetWidth(), CVPixelBufferGetHeight(), and CVPixelBufferGetBytesPerRow() returned were returning 1280, 720, and 1960 respectively. The 'bytesPerRow' value here (1960), is not wide enough to hold all the bytes for an image that is 1280 pixels wide. Seems like this is probably a bug in Apple's API.

So instead of using the value returned by CVPixelBufferGetBytesPerRow(), I used 'width * 4', and this worked just fine!

Tim
  • 875
  • 10
  • 15
  • 1
    Thanks for the additional information! Just as a small caveat it will only be width * 4 as long as you are using an RGBA or similar 4 bytes per pixel model. Also, the numbers you mention are not a bug. That function returns the correct number of bytes per row used *on hardware* (not necessarily correct for in memory). It is discussed [here](https://developer.apple.com/library/ios/qa/qa1829/_index.html) – borrrden Sep 02 '15 at 22:34