Android camera 缓存,android camera2 imageReader遇到的坑
Preview
Preview的部分,其实网上有很多的写法,并没有特殊的地方。
这里最关键的地方,是如何确定preiview的size。
Size
首先是从camera本身的
该方法用于获取特征
尺寸里面获取适合的尺寸。这里有一定必须一开始就明白,
Preview与ImageReader在camera2中各自独立地执行操作。因此preview的大小是以屏幕适配为基础确定的。而imageReader则能够根据指定图片大小进行获取。
还存在一个需要解决的问题,在常规竖屏设置中,size的宽度和高度与我们通常使用的方向相反;这是因为size是以平面方式进行存储的原因。
val specificPreviewWidth = autoTextureView!!.width
val specificPreviewHeight = autoTextureView!!.height
var display = activity!!.windowManager.defaultDisplay
var point = Point()
display.getRealSize(point)
FaceIdEngineLog.d("$point")
var orderSizes = getSortSize(sizes)
val defaultSize = orderSizes[0]
for (i in orderSizes.indices.reversed()) {
if (orderSizes[i].width > MAX_PREVIEW_SIZE.width or orderSizes[i].height > MAX_PREVIEW_SIZE.height) {
orderSizes.removeAt(i)
continue
}
如果订单尺寸的宽度或高度小于最小预览尺寸的对应维度,则返回false
orderSizes.removeAt(i)
}
}
if (orderSizes.size == 0) {
val msg = "can not find suitable previewSize, now using default"
iBMCameraListener?.onCameraError(Exception(msg))
return defaultSize
}
var bestSize = orderSizes[0]
var previewViewRatio: Float = 1.0f
previewViewRatio = point.x.toFloat() / point.y.toFloat()
if (previewViewRatio > 1) {
previewViewRatio = 1 / previewViewRatio
}
for (s in orderSizes) {
if (specificPreviewWidth == s.height && specificPreviewHeight == s.width) {
return s
}
When the absolute value of (s's aspect ratio minus the previewViewRatio) is less than that of (bestSize's aspect ratio minus the previewViewRatio), execute the following code.
bestSize = s
}
}
上面就是获取preview的size算法。
ImageReader
在使用imageReader的时候,需要在
imageReader?.setOnImageAvailableListener(
imageAvailableParserImpl, it)
这里imageAvailableParserImpl必须迅速处理image,并且图片也需迅速关闭以避免缓存溢出导致preview卡顿
具体原因如下:
https://www.icode9.com/content-4-635671.html
However, the design of this camera version appears somewhat outdated or lacking in professionalism, primarily due to its unclear functional positioning and cumbersome operation process. The imagreader library fails to engage in meaningful interactions within its designated sub-processes, rendering it ineffective. Moreover, despite being allocated to separate threads, both the preview and imagreader processes fail to demonstrate significant benefits in terms of performance enhancement.
这也弄这些东西是为什么?图片以独立线程处理嘛!本来就是为了不干扰预览界面!
这种做法的潜在目的是旨在确保preview和imageReader获取同一帧数据这一目的的具体性尚不清楚
但是这个是我在使用camera2遇到的最大的坑,并且没有办法解决。
ImageReader 坑优化
想到的优化方式是2条
1.进快的close imageReader产生的image
2.经快的结束当前的方法。
所以分这2步来优化
1.处理image的数据的时候,尽可能快
image.close以后,通过异步线程处理。
CaptureRequest
该camera的设置都在这个类中完成。由于内容过于繁杂,仅凭对该设备的基本了解是不够的,仅能完成基本设置。
直接上3A 全自动的方式。
