问题
As the title mentioned.
I search with Google and Stackoverflow, all resources are for UIImage converting, or convert NSImage FROM CVPixelBufferRef. Now what I want to do is convert JPEG raw data TO CVPixelBufferRef so that I could generate a movie file with live jpeg streams.
回答1:
You can use the following method to convert from NSImage
to 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;
}
The resulting buffer can be appended to an AVAssetWriter
via AVAssetWriterInputPixelBufferAdaptor
's appendPixelBuffer::
来源:https://stackoverflow.com/questions/17481254/how-to-convert-nsdata-object-with-jpeg-data-into-cvpixelbufferref-in-os-x