I'm trying to implement a QR Code + Barcode scanning function in my application but I only manage to scan QR codes.
I'm using ZXing as scanning library and CameraX for camera functions. In order to analyse the image capture by CameraX, I use a custom ImageAnalysis.Analyzer class to detect and decode QR codes + barcode (which is not working).
Here is my analyzer :
class MyCodeImageAnalyzer(
private val onCodeDetected: (code: Result) -> Unit
) : ImageAnalysis.Analyzer {
private val yuvFormats = mutableListOf(YUV_420_888)
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
yuvFormats.addAll(listOf(YUV_422_888, YUV_444_888))
}
}
private val reader = MultiFormatReader()
override fun analyze(image: ImageProxy) {
// We are using YUV format because, ImageProxy internally uses ImageReader to get the image
// by default ImageReader uses YUV format unless changed.
if (image.format !in yuvFormats) {
Timber.e("QRCodeAnalyzer Expected YUV, now = ${image.format}")
return
}
val data = image.planes[0].buffer.toByteArray()
val source = PlanarYUVLuminanceSource(
data,
image.width,
image.height,
0,
0,
image.width,
image.height,
false
)
val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
try {
// Whenever reader fails to detect a QR code in image
// it throws NotFoundException
val result = reader.decode(binaryBitmap)
onCodeDetected(result)
} catch (e: NotFoundException) {
e.printStackTrace()
}
image.close()
}
}
I use the MultiFormatReader which takes in account many formats including QR code and barcode. I think the problem is in the yuvFormats list but I don't know what to add in it.