如何使用AVFoundation强制iOS相机以编程方式拍照? [英] How to force iOS camera to take a picture programmatically using AVFoundation?

查看:125
本文介绍了如何使用AVFoundation强制iOS相机以编程方式拍照?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要iOS相机在没有用户输入的情况下拍照。我该怎么做呢?这是我到目前为止的代码:

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;
}

我还需要添加什么以及从哪里开始?我不想拍摄视频,只拍摄一张静止图片。另外,之后如何将图像转换为UIImage?谢谢

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

推荐答案

你有一个AVCaptureStillImageOutput, stillImageOutput 。此外,您需要将捕获会话存储在以后可以获取的位置。称之为 self.sess 。然后:

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];
     });
 }];

这篇关于如何使用AVFoundation强制iOS相机以编程方式拍照?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆