美文网首页
CGImage 转 CVPixelBuffer

CGImage 转 CVPixelBuffer

作者: 童冀 | 来源:发表于2016-08-19 10:02 被阅读989次

    应用场景:把图像流放在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

    相关文章

      网友评论

          本文标题:CGImage 转 CVPixelBuffer

          本文链接:https://www.haomeiwen.com/subject/xelbsttx.html