应用场景:把图像流放在OpenGL里渲染,需要进行一次转换
- (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通道,如其他通道需替换相关参数:kCVPixelFormatType_32BGRA,CGColorSpaceCreateDeviceRGB