And*_*rea 7 iphone image capture avfoundation ios4
我正在编写一个iPhone应用程序,使用AVFoundation从相机创建静态图像.阅读编程指南我发现了一个几乎我需要做的代码,所以我试图"逆向工程"并理解它.
我发现在理解将CMSampleBuffer转换为图像的部分时遇到了一些困难.
所以这是我理解的,后来是代码.
CMSampleBuffer表示存储器中存储有附加数据的图像的缓冲区.后来我调用函数CMSampleBufferGetImageBuffer()来仅使用图像数据接收CVImageBuffer.
现在有一个我不理解的功能,我只能想象它的功能:CVPixelBufferLockBaseAddress(imageBuffer,0); 我无法理解它是否是一个"线程锁",以避免对它进行多次操作或锁定缓冲区的地址,以避免在操作期间发生变化(为什么要更改?...另一帧,不是数据被复制在另一个地方?).剩下的代码对我来说很清楚.
试图在谷歌上搜索但仍然没有找到任何帮助.
有人可以带点光吗?
-(UIImage*) getUIImageFromBuffer:(CMSampleBufferRef) sampleBuffer{
// Get a CMSampleBuffer's Core Video image buffer for the media data
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
// Lock the base address of the pixel buffer
CVPixelBufferLockBaseAddress(imageBuffer, 0);
void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
// Get the number of bytes per row for the pixel buffer
size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
// Get the pixel buffer width and height
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
// 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);
// Unlock the pixel buffer
CVPixelBufferUnlockBaseAddress(imageBuffer,0);
// Free up the context and color space
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
// Create an image object from the Quartz image
UIImage *image = [UIImage imageWithCGImage:quartzImage];
// Release the Quartz image
CGImageRelease(quartzImage);
return (image);
}
Run Code Online (Sandbox Code Playgroud)
谢谢,安德烈
头文件说 CVPixelBufferLockBaseAddress 使内存“可访问”。我不确定这到底是什么意思,但如果你不这样做, CVPixelBufferGetBaseAddress 就会失败,所以你最好这样做。
编辑
只是做它是简短的答案。为什么要考虑该图像可能不存在于主内存中,它可能存在于某个 GPU 上某处的纹理中(CoreVideo 也适用于 mac),甚至与您期望的格式不同,因此您获得的像素实际上是一个复制。如果没有锁定/解锁或某种开始/结束对,则实现无法知道您何时完成了重复像素,因此它们会有效地泄漏。CVPixelBufferLockBaseAddress 只是提供 CoreVideo 范围信息,我不会太在意它。
是的,他们可以简单地从 CVPixelBufferGetBaseAddress 返回像素并完全消除 CVPixelBufferLockBaseAddress。我不知道他们为什么不这样做。