Convert UIImage to CVImageBufferRef

mediaspreemediaspree FloridaPosts: 895Registered Users @ @ @
edited December 2011 in iOS SDK Development
This code mostly works but the resulting data seems to be losing a color channel (or something!) The sample image I am using is of a face and the result comes out tinted blue! Here is my code:
UIImage* myImage=[UIImage imageNamed:@";sample1.png"];
CGImageRef imageRef=[myImage CGImage];
CVImageBufferRef pixelBuffer = [self pixelBufferFromCGImage:imageRef];

The pixelBufferFromCGImage method was found on stackoverflow and is as follows:
- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
    CGSize frameSize = CGSizeMake(CGImageGetWidth(image), CGImageGetHeight(image));
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:NO], kCVPixelBufferCGImageCompatibilityKey,
                             [NSNumber numberWithBool:NO], kCVPixelBufferCGBitmapContextCompatibilityKey,
    CVPixelBufferRef pxbuffer = NULL;
    CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, frameSize.width,
                                          frameSize.height,  kCVPixelFormatType_32ARGB, (CFDictionaryRef) options, 
    NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);
    CVPixelBufferLockBaseAddress(pxbuffer, 0);
    void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(pxdata, frameSize.width,
                                                 frameSize.height, 8, 4*frameSize.width, rgbColorSpace, 

    CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image), 
                                           CGImageGetHeight(image)), image);
    CVPixelBufferUnlockBaseAddress(pxbuffer, 0);
    return pxbuffer;

I've tried changing the colorspace etc. but no matter I do I get a blue image :)
Post edited by mediaspree on


Sign In or Register to comment.

Advertise here

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!