Color Distortion in CGImageCreate

I am trying to create image capture for my iOS application, but I keep getting color distortion on the result of CGImage. Here is a camera preview, the correct colors.

enter image description here

Cola red, all is well.

When I run my snapshot code, I get the following:

enter image description here

Cola is blue ... where did it come from?

I tried to mess with some parameters, but just don't get any image at all. Here is my snapshot code:

int bitsPerComponent = 8; int bitsPerPixel = 32; int bytesPerRow = [cameraVideo bufRowBytes]; CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, [cameraVideo bufDataPtr], [cameraVideo bufWidth]*[cameraVideo bufHeight]*4, NULL); CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); CGBitmapInfo bitmapInfo = kCGImageAlphaNoneSkipLast; CGColorRenderingIntent renderingIntent = kCGRenderingIntentPerceptual; CGImageRef imageRef = CGImageCreate( [cameraVideo bufWidth], [cameraVideo bufHeight], bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent); CGColorSpaceRelease(colorSpaceRef); 

I am on my way, so if anyone can understand what I'm doing wrong, let me know.

Fixed

Here is the final code:

 if (cameraVideo.ARPixelFormat == kCVPixelFormatType_32ARGB) { bitmapInfo = kCGBitmapByteOrder32Big | kCGImageAlphaNoneSkipFirst; } else { bitmapInfo = kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst; } 
+7
source share
1 answer

It looks like your R (red) and B (blue) channels are exchanging. The camera fills the buffer in BGR order, but you tell CGImage that the data is in RGB order. I believe that you control this using one of the kCGBitmapByteOrder... constants kCGBitmapByteOrder... in CGBitmapInfo . Try installing bitmapInfo as follows:

 CGBitmapInfo bitmapInfo = kCGImageAlphaNoneSkipLast | kCGBitmapByteOrder32Big; 

If this does not work, try the other kCGBitmapByteOrder... constants kCGBitmapByteOrder... ( kCGBitmapByteOrder32Little , kCGBitmapByteOrder16Big , kCGBitmapByteOrder16Little ).

EDIT

A sample Apple SquareCam project has a file called SquareCam/SqareCamViewController.m (yes, "Square" is written with an error in the file name). It contains this code:

  sourcePixelFormat = CVPixelBufferGetPixelFormatType( pixelBuffer ); if ( kCVPixelFormatType_32ARGB == sourcePixelFormat ) bitmapInfo = kCGBitmapByteOrder32Big | kCGImageAlphaNoneSkipFirst; else if ( kCVPixelFormatType_32BGRA == sourcePixelFormat ) bitmapInfo = kCGBitmapByteOrder32Little | kCGImageAlphaNoneSkipFirst; else return -95014; // only uncompressed pixel formats 

You might want to do the same.

+12
source

All Articles