【问题标题】:How to force iOS camera to take a picture programmatically using AVFoundation?如何强制 iOS 相机使用 AVFoundation 以编程方式拍照?
【发布时间】:2026-02-24 02:40:01
【问题描述】:

我需要 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 ?谢谢

【问题讨论】:

    标签: ios objective-c ios-camera


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你有一个 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];
           });
       }];
      

      【讨论】:

      • 感谢您的帮助!您能逐行解释所有这些代码的作用吗?
      【解决方案3】:

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

      Here is the sample code 拍摄带有预览层的静止图像。

      【讨论】:

        最近更新 更多