从相机缓冲区iOS转换图像。使用AVFoundation捕获静止图像

时间:2011-09-26 06:59:25

标签: ios camera uiimage buffer quartz-graphics


我正在使用Apple着名的示例代码将相机缓冲静止图像转换为UIImages。

-(UIImage*) getUIImageFromBuffer:(CMSampleBufferRef) imageSampleBuffer{

// Get a CMSampleBuffer's Core Video image buffer for the media data
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(imageSampleBuffer); 

if (imageBuffer==NULL) {
    NSLog(@"No buffer");
}

// Lock the base address of the pixel buffer 
if((CVPixelBufferLockBaseAddress(imageBuffer, 0))==kCVReturnSuccess){
    NSLog(@"Buffer locked successfully");
} 

void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer); 

// Get the number of bytes per row for the pixel buffer
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); 
NSLog(@"bytes per row %zu",bytesPerRow );
// Get the pixel buffer width and height
size_t width = CVPixelBufferGetWidth(imageBuffer); 
NSLog(@"width %zu",width);

size_t height = CVPixelBufferGetHeight(imageBuffer); 
NSLog(@"height %zu",height);

// Create a device-dependent RGB color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 

// Create a bitmap graphics context with the sample buffer data
CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, 
bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); 

// Create a Quartz image from the pixel data in the bitmap graphics context
CGImageRef quartzImage = CGBitmapContextCreateImage(context); 

// Free up the context and color space
CGContextRelease(context); 
CGColorSpaceRelease(colorSpace);

// Create an image object from the Quartz image
UIImage *image= [UIImage imageWithCGImage:quartzImage scale:SCALE_IMAGE_RATIO orientation:UIImageOrientationRight];

// Release the Quartz image
CGImageRelease(quartzImage);

// Unlock the pixel buffer
CVPixelBufferUnlockBaseAddress(imageBuffer,0);


return (image );}

问题在于您获得的图像通常是90°旋转。使用方法+ imageWithCGImage:scale:orientation我可以旋转它,但在进入这个方法之前,我试图使用CTM函数旋转和缩放图像,然后将其传递给UIImage。问题是CTM转换不影响图像 我问自己为什么......是因为我锁定了缓冲区?或者因为上下文是用里面的图像创建的,所以这些变化只影响进一步的mod?
谢谢

1 个答案:

答案 0 :(得分:0)

答案是它只影响进一步的修改,它没有处理缓冲区锁定的问题 正如你可以从这个答案中读到的那样,上下文的mod应用于时间Vertical flip of CGContext