Search code examples
iosobjective-cios6

invalid context 0x0 CGContextDrawImage


After some runs of the following block of code, I get an invalid context 0x0 for CGContextDrawImage. This code is in a user-defined method within a UIViewController. I essentially capture an image from taking a still image using AVFoundation and take that image for reading pixel hex data value. Below is the code I have written:

AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in stillImageOutput.connections)
{
    for (AVCaptureInputPort *port in [connection inputPorts])
    {
        if ([[port mediaType] isEqual:AVMediaTypeVideo] )
        {
            videoConnection = connection;
            break;
        }
    }
    if (videoConnection) { break; }
}
[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
{
    CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
    NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
    image2 = [[UIImage alloc] initWithData:imageData];
}];

CGImageRef imageRef = [image CGImage];
CGContextRef context = CGBitmapContextCreate(rawData, width, height,bitsPerComponent,bytesPerRow, colorSpace,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);

Why am I getting an invalid context 0x0 for CGContextDrawImage?


Solution

  • CGBitmapContextCreate returns NULL if it is unable to create the requested context. CGContextDrawImage is essentially complaining about context being NULL.