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

标签 ios camera uiimage buffer quartz-graphics


我正在使用来自 Apple 的众所周知的示例代码将相机缓冲区静止图像转换为 UIImage。

-(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?
谢谢

最佳答案

答案是它只影响进一步的修改,与缓冲区锁定无关。
正如您可以从这个答案模型中读到的那样,上下文是按时间应用的 Vertical flip of CGContext

关于ios - 从相机缓冲区 iOS 转换图像。使用 AVFoundation 捕获静止图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7551587/

相关文章:

使用相机后尝试编辑图片时,Android 新照片应用程序崩溃

javascript - 使用 Three.js 围绕对象旋转相机

java - 退出jframe时 Swing 停止定时器

ios - UIImage 到 CVPixelBuffer 内存问题

ios - -[__NSCFConstantString 大小] : unrecognized selector sent to instance . ..?

ios - 如何知道 Firebase 是否已获取值

ios - 当iphone到达某个位置时如何触发警报?

ios - Apple PushKit didUpdatePushCredentials 从未在 iOS 9+ 上被调用

ios - 选项卡栏快速选择索引

ios - 将 UIImage 添加到 EKEvent 标题