本文主要总结一下,如何使用avfoundation的功能来实现图像的采集,主要用到了avfoundation中的一些类,采集的结构如下图,引用自ios开发者官网:
avcapturesession
采集会话,其主要功能从整体上来掌管图像采集的过程,配置采集的行为,然后控制采集的数据从输入到输出的走向。
avcapturedevice
采集设备,简单来说就是从系统获取头像头,对于ios来说,主要是前置和后置摄像头,如下就是获取采集设备的方式:
let videodevice = avcapturedevice.default(.builtinwideanglecamera,
for: .video,
position: .unspecified)
avcapturedeviceinput
其功能就是作为avcapturesession中媒体数据的输入,使用获取到的采集设备来创建
let videoinput = try? avcapturedeviceinput(device: videodevice!)
avcapturephotooutput
作为avcapturesession的输出端,主要作用就是提供了静态图片采集工作流的接口,可输出的图片编码和文件有多种比如原始数据的dng文件,hevc格式的heif文件,以及熟知的jpeg文件等。
avcapturephotosettings
针对单次图像采集请求功能和设置的规范,在调用output的capture接口传入,本例中用得比较简单,先不展开说。比较重要的是,一个settings对象只能用于一次采集,重复使用会抛出invalidargumentexception 异常。
avcapturevideopreviewlayer
是core animation中提供的一个layer,用来展示capture的预览图像,只需要将前文提到的capture session创建完成之后设置给layer,然后capture seesion调用startrunning()之后,就能看到预览图像了。如下:
self.videopreviewlayer.session = self.mediacapture.capturesession
avcapturephotocapturedelegate
定义了获取captureoutput中状态和获取采集结果的方法。本例中在调用output的采集方法时传入,实现了photooutput(_ output: avcapturephotooutput, didfinishprocessingphoto photo: avcapturephoto, error: error?) 方法,在这个方法中获取采集到的数据。
avcapturephoto
在上面的delegate返回采集结果的方法中,有一个参数是avcapturephoto对象,通过这个对象,就可以得到采集到的数据,如下:
let photodata = photo.filedatarepresentation()
let image = uiimage(data: photodata!);
如上面所示,image中就是采集到的数据,可以使用uimageview来展示,也可以将其写入到文件中。后面我将使用metal来渲染这个采集数据。demo代码在我整理后贴出来。
在得到图片数据之后,还可以通过uiimage中的cgimage来查看图像的基本属性,如下所示:
let format: cgimagepixelformatinfo = cgimagepixelformatinfo(rawvalue: (image?.cgimage?.pixelformatinfo)!.rawvalue) ?? cgimagepixelformatinfo.rgb555
let w: int = image?.cgimage?.width ?? 0
let h: int = image?.cgimage?.height ?? 0
let components: int = image?.cgimage?.bitspercomponent ?? 0
let bits: int = image?.cgimage?.bitsperpixel ?? 0
可以得到当前图像的宽高、格式,一个像素的字节数bits,每一个components(r/g/b/a)的字节数,然后就可以得到通道数bits / components。
有一点需要的注意的,通过这个方式得到的图像是经过旋转90度、4:3的图像,在使用前需要处理一下。
推荐大家多看官方的文档,对这些类介绍得比较详细,而且smaple code也不错。但是好像swift的demo不是很多😂
发表评论