ios 如何使用 AVCaptureStillImageOutput 拍照

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20296827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 22:34:17  来源:igfitidea点击:

How To Use AVCaptureStillImageOutput To Take Picture

iosios7avfoundation

提问by Alex Pelletier

I have a preview layer that is pulling from the camera and working as it should. I would like to be able to take a picture when I press a button. I have inited the AVCaptureStillImageOutput like this:

我有一个从相机中拉出并正常工作的预览层。我希望能够在按下按钮时拍照。我已经像这样初始化了 AVCaptureStillImageOutput:

AVCaptureStillImageOutput *avCaptureImg = [[AVCaptureStillImageOutput alloc] init];

Then I am trying to take a picture using this object:

然后我尝试使用这个对象拍照:

[avCaptureImg captureStillImageAsynchronouslyFromConnection:(AVCaptureConnection *) completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {  }];

I need help on how to take a picture and save it in a variable. Thanks

我需要有关如何拍摄照片并将其保存在变量中的帮助。谢谢

回答by vfxdrummer

You need to be sure to define a AVCaptureVideoPreviewLayer & add it to a view layer :

您需要确保定义一个 AVCaptureVideoPreviewLayer 并将其添加到视图层:

AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
[self.view.layer addSublayer:captureVideoPreviewLayer];

This will be connected to your AVCaptureDeviceInput

这将连接到您的 AVCaptureDeviceInput

Here's the full solution :

这是完整的解决方案:

/////////////////////////////////////////////////
////
//// Utility to find front camera
////
/////////////////////////////////////////////////
-(AVCaptureDevice *) frontFacingCameraIfAvailable{

    NSArray *videoDevices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    AVCaptureDevice *captureDevice = nil;

   for (AVCaptureDevice *device in videoDevices){

        if (device.position == AVCaptureDevicePositionFront){

            captureDevice = device;
            break;
        }
    }

    //  couldn't find one on the front, so just get the default video device.
    if (!captureDevice){

        captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    }

    return captureDevice;
}

/////////////////////////////////////////////////
////
//// Setup Session, attach Video Preview Layer
//// and Capture Device, start running session
////
/////////////////////////////////////////////////
-(void) setupCaptureSession {
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    session.sessionPreset = AVCaptureSessionPresetMedium;

    AVCaptureVideoPreviewLayer *captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer    alloc] initWithSession:session];
    [self.view.layer addSublayer:captureVideoPreviewLayer];

    NSError *error = nil;
    AVCaptureDevice *device = [self frontFacingCameraIfAvailable];
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    if (!input) {
        // Handle the error appropriately.
        NSLog(@"ERROR: trying to open camera: %@", error);
    }
    [session addInput:input];

    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys: AVVideoCodecJPEG, AVVideoCodecKey, nil];
    [self.stillImageOutput setOutputSettings:outputSettings];

    [session addOutput:self.stillImageOutput];

    [session startRunning];
}


/////////////////////////////////////////////////
////
//// Method to capture Still Image from 
//// Video Preview Layer
////
/////////////////////////////////////////////////
-(void) captureNow {
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in self.stillImageOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }

    NSLog(@"about to request a capture from: %@", self.stillImageOutput);
    __weak typeof(self) weakSelf = self;
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {

         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         UIImage *image = [[UIImage alloc] initWithData:imageData];

         [weakSelf displayImage:image];
     }];
}

回答by William Hu

for swift version:

对于快速版本:

@IBAction func capture(sender: AnyObject) {

    var videoConnection :AVCaptureConnection?

    if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo){
        stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (buffer:CMSampleBuffer!, error: NSError!) -> Void in

            if let exifAttachments = CMGetAttachment(buffer, kCGImagePropertyExifDictionary, nil) {
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
                self.previewImage.image = UIImage(data: imageData)
                UIImageWriteToSavedPhotosAlbum(self.previewImage.image, nil, nil, nil)
            }
        })
    }
}

回答by Jay Gajjar

-(void)captureImage:(NSString *)string successCallback:(void (^)(id))successCallback errorCallback:(void (^)(NSString *))errorCallback{

    __block UIImage *image;
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in stillImageOutput.connections)
    {
        for (AVCaptureInputPort *port in [connection inputPorts])
        {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] )
            {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection)
        {
            break;
        }
    }

    //NSLog(@"about to request a capture from: %@", stillImageOutput);
    [videoConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];

    [stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error)
     {
         CFDictionaryRef exifAttachments = CMGetAttachment( imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
         if (exifAttachments)
         {
             // Do something with the attachments.
             //NSLog(@"attachements: %@", exifAttachments);
         } else {
             //NSLog(@"no attachments");
         }

         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         image = [[UIImage alloc] initWithData:imageData];


         successCallback(image);
         //UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
     }];


    NSError *error;
    if (error) {
        errorCallback(@"error");
    }else{

    }
}

回答by Alex Pelletier

Not sure why I didn't see this sooner:

不知道为什么我没有早点看到这个:

iPhone SDK 4 AVFoundation - How to use captureStillImageAsynchronouslyFromConnection correctly?

iPhone SDK 4 AVFoundation - 如何正确使用 captureStillImageAsynchronouslyFromConnection?

Adams answer works fantastic!

亚当斯的回答太棒了!