iOS10相机API适配一

iOS10在拍照方面的API主要有以下几个亮点:

  • 部分机型支持LivePhoto的拍摄和编辑
  • 部分机型支持RawPhoto的拍摄和编辑
  • 支持拍照时快速获取预览图

LivePhoto拍摄

  • 创建AVCapturePhotoOutput
  • 添加AudioInput
  • 设置livePhotoCaptureEnabled属性为YES
  • 创建AVCapturePhotoSettings实例,并设置livePhotoMovieFileURL属性
  • 获取LivePhoto数据
- (void)captureOutput:(AVCapturePhotoOutput *)captureOutput
didFinishProcessingLivePhotoToMovieFileAtURL:(NSURL *)outputFileURL
             duration:(CMTime)duration
     photoDisplayTime:(CMTime)photoDisplayTime
     resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings
                error:(NSError *)error
{
	 // do something...
}
注意:
  • 必须将AVCapturePhotoOutput实例先加入AVCaptureSession的output中,再设置livePhotoMovieFileURL,否则会设置失败.
  • LivePhoto只支持分辨率模式为AVCaptureSessionPresetPhoto
  • LivePhoto的本质就是一个视频文件

RawPhoto拍摄

  • 创建AVCapturePhotoOutput

  • 设置FormatType

NSUInteger rawFormat = photoOutput.availableRawPhotoPixelFormatTypes.firstObject.unsignedIntegerValue;
photoSettings = [AVCapturePhotoSettings photoSettingsWithRawPixelFormatType:(OSType)rawFormat];
  • 保存DNG文件
- (void)captureOutput:(AVCapturePhotoOutput *)captureOutput
didFinishProcessingRawPhotoSampleBuffer:(CMSampleBufferRef)rawSampleBuffer
previewPhotoSampleBuffer:(CMSampleBufferRef)previewPhotoSampleBuffer
     resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings
      bracketSettings:(AVCaptureBracketedStillImageSettings *)bracketSettings
                error:(NSError *)error {
    NSData *data = [AVCapturePhotoOutput DNGPhotoDataRepresentationForRawSampleBuffer:rawSampleBuffer previewPhotoSampleBuffer:previewPhotoSampleBuffer];
    NSString *filePath = [dir stringByAppendingPathExtension:@"dng"];
    [data writeToFile:filePath atomically:YES];
    // do something...
}

获取快速预览图

  • 在代理方法中通过参数能够获取preview的sampleBuffer
  • 有个问题是这个sampleBuffer并不是压缩过的JPEG数据,也没有Exif信息,所以并不能通过这个数据获取预览图的方向信息,我能想到的解决办法有两个: 1) 通过原片的Exif信息来处理预览图。2) 通过拍照时一瞬间的设备方向来纠正方向。
- (void)captureOutput:(AVCapturePhotoOutput *)captureOutput
didFinishProcessingPhotoSampleBuffer:(CMSampleBufferRef)photoSampleBuffer
previewPhotoSampleBuffer:(CMSampleBufferRef)previewPhotoSampleBuffer
     resolvedSettings:(AVCaptureResolvedPhotoSettings *)resolvedSettings
      bracketSettings:(AVCaptureBracketedStillImageSettings *)bracketSettings
                error:(NSError *)error {
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(previewPhotoSampleBuffer);
    CIImage *ciImage = [CIImage imageWithCVImageBuffer:imageBuffer];
    UIImage *previewImage = [UIImage imageWithCIImage:ciImage];
    // do something...
}

Updated:

Comments