【iOS初学笔记】CMSampleBufferRef 转 UIImage
2015-02-06 23:57
981 查看
用AVFoundation捕捉视频帧,很多时候需要把某一帧转换成UIImage,用此函数:
当然,先不要急,因为捕捉到得帧是YUV颜色通道的,这种颜色通道无法通过以上函数转换,RGBA颜色通道才可以成功转换,所以,先需要把视频帧的输出格式设置一下:
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer { // 为媒体数据设置一个CMSampleBuffer的Core Video图像缓存对象 CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer); // 锁定pixel buffer的基地址 CVPixelBufferLockBaseAddress(imageBuffer, 0); // 得到pixel buffer的基地址 void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer); // 得到pixel buffer的行字节数 size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer); // 得到pixel buffer的宽和高 size_t width = CVPixelBufferGetWidth(imageBuffer); size_t height = CVPixelBufferGetHeight(imageBuffer); // 创建一个依赖于设备的RGB颜色空间 CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); // 用抽样缓存的数据创建一个位图格式的图形上下文(graphics context)对象 CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst); // 根据这个位图context中的像素数据创建一个Quartz image对象 CGImageRef quartzImage = CGBitmapContextCreateImage(context); // 解锁pixel buffer CVPixelBufferUnlockBaseAddress(imageBuffer,0); // 释放context和颜色空间 CGContextRelease(context); CGColorSpaceRelease(colorSpace); // 用Quartz image创建一个UIImage对象image UIImage *image = [UIImage imageWithCGImage:quartzImage]; // 释放Quartz image对象 CGImageRelease(quartzImage); return (image); }
当然,先不要急,因为捕捉到得帧是YUV颜色通道的,这种颜色通道无法通过以上函数转换,RGBA颜色通道才可以成功转换,所以,先需要把视频帧的输出格式设置一下:
[videoOutput setVideoSettings:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA] forKey:(id)kCVPixelBufferPixelFormatTypeKey]];
相关文章推荐
- CMSampleBufferRef 与 UIImage 的转换
- CMSampleBufferRef 与 UIImage 的转换
- CMSampleBufferRef转UIImage
- CMSampleBufferRef获取h264 char*数据及sps/pps
- get buffer from CMSampleBufferRef
- CMSampleBufferRef与byte*互相转换(audio)
- CMSampleBufferRef与byte*互相转换
- CMSampleBufferRef转CIImage
- CMSampleBufferRef与byte*互相转换(audio)
- CMSampleBufferRef转换为nsdata对象
- CMSampleBufferRef TO NSData
- 【iOS初学笔记】翻转UIImage
- iOS CMSampleBuffer deep copy
- 【初学】iOS学习笔记-本地化之Plist文件读写操作
- ios学习临时笔记-UIImage拉伸
- IOS开发笔记之十五——UIImage图片的移动、旋转、缩放和裁剪
- 初学ios的一些笔记
- 【iOS初学笔记】ASIHTTPRequest库返回UTF8数据
- IOS学习笔记(十)之UIImageView图片视图的基本概念和使用方法
- iOS开发笔记--UIImageView的属性之animationImages详解