1

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

-(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 ?谢谢

4

3 回答 3

1

你有一个 AVCaptureStillImageOutput, stillImageOutput. 另外,您需要存储您的捕获会话,以便以后获取。调用它self.sess。然后:

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];
     });
 }];
于 2014-03-15T22:08:54.593 回答
1

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

查看 AVCaptureSession,了解如何在没有用户输入的情况下拍照。您需要将相机的 AVCaptureDevice 添加到会话中。

于 2014-03-15T16:46:48.310 回答
0

正如@Salil 所说,Apple 的官方 AVFoundation 非常有用,看一下以了解主要概念。然后你可以下载一个示例代码来看看如何实现目标。

这是使用预览层拍摄静止图像的示例代码。

于 2014-06-18T15:21:26.973 回答