IOS 11 全网首发使用AVCapturePhotoOutpu
2017-12-06 本文已影响495人
水中沚_b078
首先给出几篇文章让大家了解一下什么是 HIEF(HEIC)
官方的链接--一个pdf文件
HEIF & HEVC 你知道多少
iOS 影音新格式 HEIF HEVC
GitHubHEIC扩展方法
关于AVCapturePhotoOutput,大家可以参考一下下面的链接,就知道怎么使用了,从ios11开始我们就可以使用HIEF(HEIC)格式来存储图片和视频了.这种格式体积小速度快(硬解码),所以作为一个android程序员的我看到这种好玩的东西也忍不住来凑热闹, 但是找了很多资料,都没有如何直接捕获(不是通过JPEG转换)HEIF(HEIC)格式图片.
ios 11新增了一个方法
- (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(nullable NSError *)error NS_AVAILABLE_IOS(11_0);
新增了一种采集格式AVVideoCodecHEVC
接下来就是上关键源码
开始拍照
关键代码@{AVVideoCodecKey: AVVideoCodecHEVC}
原来的是{AVVideoCodecKey: AVVideoCodecJPEG}
注意_outputSettings必须每次都用新的
if (@available(iOS 10.0, *)) {
AVCapturePhotoOutput *_newCaptureImageOutput = (AVCapturePhotoOutput *) _captureImageOutput;
// 图片输出格式,如果支持使用HEIF(HEIC)那么使用,否则使用JPEG
NSDictionary *format = @{AVVideoCodecKey: AVVideoCodecJPEG};
NSArray<AVVideoCodecType> *availablePhotoCodecTypes = _newCaptureImageOutput.availablePhotoCodecTypes;
if ([availablePhotoCodecTypes containsObject:AVVideoCodecHEVC]) {
format = @{AVVideoCodecKey: AVVideoCodecHEVC};
}
_outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:format];
_outputSettings.autoStillImageStabilizationEnabled = YES;//默认值就是yes
_outputSettings.flashMode = AVCaptureFlashModeOff;//关闭闪光灯
// 预览图设置
id photoPixelFormatType = _outputSettings.availablePreviewPhotoPixelFormatTypes.firstObject;
NSDictionary *preview =
@{
(NSString *) kCVPixelBufferPixelFormatTypeKey: photoPixelFormatType,
(NSString *) kCVPixelBufferWidthKey: @1440,
(NSString *) kCVPixelBufferHeightKey: @1440
};
_outputSettings.previewPhotoFormat = preview;
// 缩略图设置
id thumbnailPhotoCodecType = _outputSettings.availableEmbeddedThumbnailPhotoCodecTypes.firstObject;
NSDictionary *thumbnail =
@{
(NSString *) kCVPixelBufferPixelFormatTypeKey: thumbnailPhotoCodecType,
(NSString *) kCVPixelBufferWidthKey: @(NBUAsset.thumbnailSize.width),
(NSString *) kCVPixelBufferHeightKey: @(NBUAsset.thumbnailSize.height)
};
//_outputSettings.embeddedThumbnailPhotoFormat = thumbnail;
[_newCaptureImageOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
[_newCaptureImageOutput capturePhotoWithSettings:_outputSettings delegate:self];
return;
}
监听 继承AVCapturePhotoCaptureDelegate
- (void) captureOutput:(AVCapturePhotoOutput *)output
didFinishProcessingPhoto:(AVCapturePhoto *)photo
error:(nullable NSError *)error NS_AVAILABLE_IOS(11_0) {
// 这个就是HEIF(HEIC)的文件数据,直接保存即可
NSData *data = photo.fileDataRepresentation;
UIImage *image = [UIImage imageWithData:data];
// 保存图片到相册 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
}