CGBitmapContextCreate returns NULL

4.8k views Asked by At

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.

2

There are 2 answers

1
graver On BEST ANSWER

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.

1
Tim On

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!