转自http://www.jianshu.com/p/a91502c00fb0
CMSampleBufferRef 与 UIImage 的转换
在取得 CMSampleBufferRef 之后,还必须透过一连串的转换才能够得到 UIImage,CMSampleBufferRef –> CVImageBufferRef –> CGContextRef –> CGImageRef –> UIImage,你可以将以下程序代码任意实作于上述两个内部函数中来取得连续影像片段中的 UIImage。
//制作 CVImageBufferRef
CVImageBufferRef buffer;
buffer = CMSampleBufferGetImageBuffer(sampleBuffer);
CVPixelBufferLockBaseAddress(buffer, 0);
//从 CVImageBufferRef 取得影像的细部信息
uint8_t *base;
size_t width, height, bytesPerRow;
base = CVPixelBufferGetBaseAddress(buffer);
width = CVPixelBufferGetWidth(buffer);
height = CVPixelBufferGetHeight(buffer);
bytesPerRow = CVPixelBufferGetBytesPerRow(buffer);
//利用取得影像细部信息格式化 CGContextRef
CGColorSpaceRef colorSpace;
CGContextRef cgContext;
colorSpace = CGColorSpaceCreateDeviceRGB();
cgContext = CGBitmapContextCreate(base, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
//透过 CGImageRef 将 CGContextRef 转换成 UIImage
CGImageRef cgImage;
UIImage *image;
cgImage = CGBitmapContextCreateImage(cgContext);
image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
CGContextRelease(cgContext);
CVPixelBufferUnlockBaseAddress(buffer, 0);
//成功转换成 UIImage
//[myImageView setImage:image];
最后,如果你希望改变撷取影像时的方向,则可以对内部函数中的 AVCaptureConnection 做 setVideoOrientation: 旋转影像,或 setVideoMirrored: 镜射影像。