Capturing iSight image using AVFoundation on Mac

若如初见. 提交于 2019-12-05 05:19:51

Alright, I found the solution!! Here it is:

- (void)takePicture
{
    NSError* error;
    AVCaptureDevice* device = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];
    AVCaptureDeviceInput* input = [AVCaptureDeviceInput deviceInputWithDevice: device error: &error];
    if (!input) {
        _error = error;
        _done = YES;
        return;
    }

    AVCaptureStillImageOutput* output = [AVCaptureStillImageOutput new];
    [output setOutputSettings: @{(id)kCVPixelBufferPixelFormatTypeKey: @(k32BGRAPixelFormat)}];

    captureSession = [AVCaptureSession new];
    captureSession.sessionPreset = AVCaptureSessionPresetPhoto;

    [captureSession addInput: input];
    [captureSession addOutput: output];
    [captureSession startRunning];

    AVCaptureConnection* connection = [output connectionWithMediaType: AVMediaTypeVideo];
    [output captureStillImageAsynchronouslyFromConnection: connection completionHandler: ^(CMSampleBufferRef sampleBuffer, NSError* error) {
        if (error) {
            _error = error;
            _result = nil;
        }
        else {
            CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

            if (imageBuffer) {
                CVBufferRetain(imageBuffer);

                NSCIImageRep* imageRep = [NSCIImageRep imageRepWithCIImage: [CIImage imageWithCVImageBuffer: imageBuffer]];

                _result = [[NSImage alloc] initWithSize: [imageRep size]];
                [_result addRepresentation: imageRep];

                CVBufferRelease(imageBuffer);
            }
        }

        _done = YES;
    }];
}

I hope this helps whoever has any problems in doing this same thing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!