How to force iOS camera to take a picture programmatically using AVFoundation?

Deadly 提交于 2019-11-28 11:12:47

问题


I need the iOS camera to take a picture without any input from the user. How would I go about doing this? This is my code so far:

-(void)initCapture{
    AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] init];

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

    NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
                                AVVideoCodecJPEG, AVVideoCodecKey,
                                nil];


    [newStillImageOutput setOutputSettings:outputSettings];


    AVCaptureSession *newCaptureSession = [[AVCaptureSession alloc] init];

    if ([newCaptureSession canAddInput:newVideoInput]) {
        [newCaptureSession addInput:newVideoInput];
    }
    if ([newCaptureSession canAddOutput:newStillImageOutput]) {
        [newCaptureSession addOutput:newStillImageOutput];
    }
    self.stillImageOutput = newStillImageOutput;
}

What else do I need to add and where do I go from here? I don't want to take a video, only a single still image. Also, how would I convert the image into a UIImage afterwards? Thanks


回答1:


https://developer.apple.com/library/mac/documentation/AVFoundation/Reference/AVCaptureSession_Class/Reference/Reference.html

Look at AVCaptureSession on how to take take picture without user input. You will need to add AVCaptureDevice for camera to the session.




回答2:


You've got an AVCaptureStillImageOutput, stillImageOutput. Plus you need to have stored your capture session where you can get at it later. Call it self.sess. Then:

AVCaptureConnection *vc = 
    [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
[self.sess startRunning];
[self.stillImageOutput captureStillImageAsynchronouslyFromConnection:vc
                                          completionHandler:
 ^(CMSampleBufferRef buf, NSError *err) {
     NSData* data = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:buf];
     UIImage* im = [UIImage imageWithData:data];
     dispatch_async(dispatch_get_main_queue(), ^{
         UIImageView* iv = [[UIImageView alloc] initWithFrame:someframe];
         iv.contentMode = UIViewContentModeScaleAspectFit;
         iv.image = im;
         [self.view addSubview: iv];
         [self.iv removeFromSuperview]; // in case we already did this
         self.iv = iv;
         [self.sess stopRunning];
     });
 }];



回答3:


As @Salil says, the apple's official AVFoundation is very useful, take a look at that to understand main concept. Then you can download a sample code to see how to achieve the goal.

Here is the sample code to take still images with a preview layer.



来源:https://stackoverflow.com/questions/22426293/how-to-force-ios-camera-to-take-a-picture-programmatically-using-avfoundation

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