macos - CMSampleBufferGetImageBuffer 为捕获的 JPEG stillImage 返回 nil
问题描述
我使用JPEG格式捕获Mac屏幕,然后获取捕获的JPEG样本缓冲区的pixelBuffer和imageBuffer。但是,pixelBuffer 始终为零,而当我将 JPEG 缓冲区转换为 NSImage 时,可以成功获取并显示图像。
-(void)createSession
{
if(self.session == nil)
{
self.session = [[AVCaptureSession alloc] init];
self.session.sessionPreset = AVCaptureSessionPresetPhoto;
CGDirectDisplayID displayId = [self getDisplayID];
self.input = [[AVCaptureScreenInput alloc] initWithDisplayID:displayId];
[self.session addInput:self.input];
self.imageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = @{AVVideoCodecKey : AVVideoCodecJPEG};
[self.imageOutput setOutputSettings:outputSettings];
[self.session addOutput:self.imageOutput];
[self.session startRunning];
}
}
-(void)processSampleBuffer
{
AVCaptureConnection *videoConnection = nil;
for (AVCaptureConnection *connection in self.imageOutput.connections) {
for (AVCaptureInputPort *port in [connection inputPorts]) {
if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
videoConnection = connection;
break;
}
}
if (videoConnection) { break; }
}
[self.imageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError * error) {
if(imageDataSampleBuffer != nil)
{
NSData * imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
self.image = [[NSImage alloc] initWithData:imageData];
CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(imageDataSampleBuffer);
CVPixelBufferLockBaseAddress(imageBuffer,0);
size_t width = CVPixelBufferGetWidth(imageBuffer);
size_t height = CVPixelBufferGetHeight(imageBuffer);
NSLog(@"width %zu height %zu", width,height);
CVPixelBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(imageDataSampleBuffer);
float width1 = CVPixelBufferGetWidth(pixelBuffer);
float height1 = CVPixelBufferGetHeight(pixelBuffer);
NSLog(@"Pixelbuffer width %f height %f", width1,height1);
}
else
{
NSLog(@"error");
}
}];
}
在 processSampleBuffer 中 self.image 可以得到一个 NSImage 并成功显示在 NSImageView 中。但 imageBuffer 和 pixelBuffer 都是零。
这让我很困惑,有人可以帮忙看看吗?
解决方案
好的,最后,我在这里找到了答案,希望它可以帮助其他人。
讨论
如果您请求以 RAW 格式或未经压缩的已处理格式(如 TIFF)捕获照片,则可以使用此属性来访问基础样本缓冲区。
如果您请求以压缩格式(例如 JPEG 或 HEVC/HEIF)进行捕获,则此属性的值为 nil。使用 fileDataRepresentation 或 CGImageRepresentation 方法获取压缩图像数据。
推荐阅读
- c# - 获取 dll 的路径 - 原始路径,而不是阴影程序集
- java - java cmd进程中如何按顺序执行多个命令
- java - 带有流弹簧引导的 DTO 映射
- java - 如何让处理在文本文件中获取数组的一项并对其做出决定
- image - 取消选择时停止 Gimp 合并图层
- angular-calendar - 角日历 | 需要一个默认的滚动视图到 8AM-11PM 在日/周中具有固定的标题
- django - 如何通过按下按钮更新 Django 中的页面
- oracle - 无法在 Oracle SQL Developer v19.0.1 中创建 PRIVATE TEMPORARY TABLE(错误:ORA-00905)
- go - 我应该在哪里存储服务注册服务器的端点?
- angular - Array.push() 增加全局条目数量