iOS 10 - Objective-C:如何实现AVCapturePhotoOutput()来捕获图像和视频?

时间:2016-10-05 11:18:00

标签: ios objective-c iphone ios10 avcapturesession

我正在尝试从我的应用中实现捕获图像和视频,现在从iOS 10开始“AVCaptureStillImageOutput”已弃用。

请帮我在Objective-C中实施 AVCapturePhotoOutput

以下是我的示例代码:

_avCaptureOutput = [[AVCapturePhotoOutput alloc]init];
_avSettings = [AVCapturePhotoSettings photoSettings];


AVCaptureSession* captureSession = [[AVCaptureSession alloc] init];
[captureSession startRunning];



AVCaptureConnection *connection = [self.movieOutput connectionWithMediaType:AVMediaTypeVideo];

if (connection.active)
{
    //connection is active
    NSLog(@"Connection is active");

    id previewPixelType = _avSettings.availablePreviewPhotoPixelFormatTypes.firstObject;
    NSDictionary *format = @{(NSString*)kCVPixelBufferPixelFormatTypeKey:previewPixelType,(NSString*)kCVPixelBufferWidthKey:@160,(NSString*)kCVPixelBufferHeightKey:@160};

    _avSettings.previewPhotoFormat = format;

    [_avCaptureOutput capturePhotoWithSettings:_avSettings delegate:self];


}
else
{
    NSLog(@"Connection is not active");
    //connection is not active
    //try to change self.captureSession.sessionPreset,
    //or change videoDevice.activeFormat
}

1 个答案:

答案 0 :(得分:8)

_avCaptureOutput = [[AVCapturePhotoOutput alloc]init];
_avSettings = [AVCapturePhotoSettings photoSettings];

AVCaptureSession* captureSession = [[AVCaptureSession alloc] init];
[captureSession startRunning];

[self.avCaptureOutput capturePhotoWithSettings:self.avSettings delegate:self];

self必须实现AVCapturePhotoCaptureDelegate

#pragma mark - AVCapturePhotoCaptureDelegate
-(void)captureOutput:(AVCapturePhotoOutput *)captureOutput didFinishProcessingPhotoSampleBuffer:(CMSampleBufferRef)photoSampleBuffer previewPhotoSampleBuffer:(CMSampleBufferRef)previewPhotoSampleBuffer resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings bracketSettings:(AVCaptureBracketedStillImageSettings *)bracketSettings error:(NSError *)error
{
    if (error) {
        NSLog(@"error : %@", error.localizedDescription);
    }

    if (photoSampleBuffer) {
        NSData *data = [AVCapturePhotoOutput JPEGPhotoDataRepresentationForJPEGSampleBuffer:photoSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
        UIImage *image = [UIImage imageWithData:data];
    }
}

现在,你得到了图像,并做任何你想做的事。

注意:由于iOS 11,-captureOutput:didFinishProcessingPhotoSampleBuffer:...已弃用,因此需要使用-captureOutput:didFinishProcessingPhoto:error:代替:

- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(nullable NSError *)error
{  
  NSData *imageData = [photo fileDataRepresentation];
  UIImage *image = [UIImage imageWithData:data];
  ...
}