如何将带有JPEG数据的NSData对象转换为OS X中的CVPixelBufferRef?

时间:2013-07-05 04:47:54

标签: macos cocoa jpeg avfoundation

如标题所述。

我使用Google和Stackoverflow搜索,所有资源都用于UIImage转换,或转换NSImage FROM CVPixelBufferRef。现在我要做的是将JPEG原始数据转换为CVPixelBufferRef,以便我可以使用实时jpeg流生成电影文件。

1 个答案:

答案 0 :(得分:4)

您可以使用以下方法将NSImage转换为CVPixelBufferRef

- (CVPixelBufferRef)newPixelBufferFromNSImage:(NSImage*)image
{
    CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    NSDictionary* pixelBufferProperties = @{(id)kCVPixelBufferCGImageCompatibilityKey:@YES, (id)kCVPixelBufferCGBitmapContextCompatibilityKey:@YES};
    CVPixelBufferRef pixelBuffer = NULL;
    CVPixelBufferCreate(kCFAllocatorDefault, [image size].width, [image size].height, k32ARGBPixelFormat, (__bridge CFDictionaryRef)pixelBufferProperties, &pixelBuffer);
    CVPixelBufferLockBaseAddress(pixelBuffer, 0);
    void* baseAddress = CVPixelBufferGetBaseAddress(pixelBuffer);
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(pixelBuffer);
    CGContextRef context = CGBitmapContextCreate(baseAddress, [image size].width, [image size].height, 8, bytesPerRow, colorSpace, kCGImageAlphaNoneSkipFirst);
    NSGraphicsContext* imageContext = [NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO];
    [NSGraphicsContext saveGraphicsState];
    [NSGraphicsContext setCurrentContext:imageContext];
    [image compositeToPoint:NSMakePoint(0.0, 0.0) operation:NSCompositeCopy];
    [NSGraphicsContext restoreGraphicsState];
    CVPixelBufferUnlockBaseAddress(pixelBuffer, 0);
    CFRelease(context);
    CGColorSpaceRelease(colorSpace);
    return pixelBuffer;
}

结果缓冲区可以通过AVAssetWriter AVAssetWriterInputPixelBufferAdaptor

附加到appendPixelBuffer::