步驟:CMSampleBufferRef --->CVImageBufferRef--->CGImageRef--->UIImage
-
(UIImage *)convertSampleBufferToImage:(CMSampleBufferRef)sampleBuffer
{
//制作 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 轉(zhuǎn)換成 UIImage
CGImageRef cgImage;
UIImage *image;
cgImage = CGBitmapContextCreateImage(cgContext);
image = [UIImage imageWithCGImage:cgImage];
CGImageRelease(cgImage);
CGContextRelease(cgContext);CVPixelBufferUnlockBaseAddress(buffer, 0);
return image;
}