應(yīng)用場(chǎng)景:把圖像流放在OpenGL里渲染,需要進(jìn)行一次轉(zhuǎn)換
- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image
{
CVPixelBufferRef pxbuffer = NULL;
NSCParameterAssert(NULL != image);
size_t originalWidth = CGImageGetWidth(image);
size_t originalHeight = CGImageGetHeight(image);
NSMutableData *imageData = [NSMutableData dataWithLength:originalWidth*originalHeight*4];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef cgContext = CGBitmapContextCreate([imageData mutableBytes], originalWidth, originalHeight, 8, 4*originalWidth, colorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(cgContext, CGRectMake(0, 0, originalWidth, originalHeight), image);
CGContextRelease(cgContext);
CGImageRelease(image);
unsigned char *pImageData = (unsigned char *)[imageData bytes];
CFDictionaryRef empty;
empty = CFDictionaryCreate(kCFAllocatorDefault, NULL, NULL,
0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFMutableDictionaryRef m_pPixelBufferAttribs = CFDictionaryCreateMutable(kCFAllocatorDefault,
3,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(m_pPixelBufferAttribs, kCVPixelBufferIOSurfacePropertiesKey, empty);
CFDictionarySetValue(m_pPixelBufferAttribs, kCVPixelBufferOpenGLCompatibilityKey, empty);
CFDictionarySetValue(m_pPixelBufferAttribs, kCVPixelBufferCGBitmapContextCompatibilityKey, empty);
CVPixelBufferCreateWithBytes(kCFAllocatorDefault, originalWidth, originalHeight, kCVPixelFormatType_32BGRA, pImageData, originalWidth * 4, NULL, NULL, m_pPixelBufferAttribs, &pxbuffer);
CFRelease(empty);
CFRelease(m_pPixelBufferAttribs);
return pxbuffer;
}
注意colorspace 是否為RGB通道,如其他通道需替換相關(guān)參數(shù):kCVPixelFormatType_32BGRA,CGColorSpaceCreateDeviceRGB