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

11

我正试图从我的应用程序中实现捕获图像和视频,而从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
}

AVCapturePhotoOutput的目的是什么? - Jagveer Singh
你实现了 AVCapturePhotoCaptureDelegate 吗? - ricardopereira
self.movieOutput 是什么类型? - ricardopereira
self.movieOutput是AVCaptureMovieFileOutput类的一种。是的,我已经实现了AVCapturePhotoCaptureDelegate方法。 - Anand Kore
1个回答

12
_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];
  ...
}

非常容易的实现 - Robert Bentley
你怎么从中获取预览照片? - user2995344

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接