首页 > 解决方案 > 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 都是零。

这让我很困惑,有人可以帮忙看看吗?

标签: macosjpegcvpixelbuffercmsamplebuffer

解决方案


好的,最后,我在这里找到了答案,希望它可以帮助其他人。

https://developer.apple.com/documentation/avfoundation/avcapturephoto/2873914-pixelbuffer?language=objc

讨论

如果您请求以 RAW 格式或未经压缩的已处理格式(如 TIFF)捕获照片,则可以使用此属性来访问基础样本缓冲区。

如果您请求以压缩格式(例如 JPEG 或 HEVC/HEIF)进行捕获,则此属性的值为 nil。使用 fileDataRepresentation 或 CGImageRepresentation 方法获取压缩图像数据。


推荐阅读