I am generating Data Matrix barcode using Zxing library. After generating i am passing generated image bitmap to next Activity after converting it into byte array(cause otherwise i will get an error). On the next activity i am converting it back to bitmap and scanning it using Firebase Google ML Kit. The success rate is only 5 in 100 times. Moreover if i save the generated barcode in my local device and scan it using CameraX Api, i am able to scan the generated barcode everytime. Is this because i am converting the bitmap back and forth? or there is something else that i am missing. Is this because of this by official documentation ->
For a Data Matrix code to be recognized, the code must intersect the center point of the input image. Consequently, only one Data Matrix code can be recognized in an image.
Here is the code Code to generate Barcode:
fun createBarcode(code: String, barcodeFormat: BarcodeFormat = BarcodeFormat.QR_CODE, width: Int? = 400, height: Int? = 400): Bitmap? {
val multiFormatWriter = MultiFormatWriter()
val bitmap: Bitmap?
return try {
val bitMatrix = multiFormatWriter.encode(code, barcodeFormat, width!!, height!!)
val barcodeEncoder = BarcodeEncoder()
bitmap = barcodeEncoder.createBitmap(bitMatrix)
bitmap
} catch (e: Exception) {
CustomException(e.message, cause = e.cause)
null
}
}
Code to Scan generated bitmap:
fun scanGalleryImage(context: Context, imageBitmap: Bitmap, onScanSuccess: (barcodeDetails: BarcodeDetail) -> Unit): BarcodeDetail? {
var barcodeDetails: BarcodeDetail? = null
val options = BarcodeScannerOptions.Builder()
.setBarcodeFormats(
AppConstants.qrFormatList[0],
*AppConstants.qrFormatList.drop(1).toIntArray()
)
.build()
val scanner = BarcodeScanning.getClient(options)
try {
val image = InputImage.fromBitmap(imageBitmap,0)
scanner.process(image)
.addOnSuccessListener { barcode ->
if(barcode != null && barcode.isNotEmpty()) {
barcodeDetails = ScannerUtility.getBarcodeDetails(barcode = barcode.first())
onScanSuccess.invoke(barcodeDetails!!)
} else {
ToastUtility.showError(context, context.resources.getString(R.string.error_invalid_qr_image), Toast.LENGTH_LONG)
}
}
.addOnFailureListener {
ToastUtility.showError(context, context.resources.getString(R.string.error_invalid_qr_image), Toast.LENGTH_LONG)
}
return barcodeDetails
} catch (e: IOException) {
CustomException(e.message,null, e.cause)
return barcodeDetails
}
}
Code to convert bitmap to byte array & byte array to bitmap:
val bitmap = ScannerService.createBarcode(productCode!!, BarcodeFormat.DATA_MATRIX, height = 100, width = 100)
val byteArray = AppUtility.getByteArray(bitmap)
activity.onCodeGenerated(byteArray)
val byteArray = intent.getByteArrayExtra(IMAGE_KEY_EXTRA)
generatedImage = BitmapFactory.decodeByteArray(byteArray, 0, byteArray!!.size)
P.S. This code is working for all other barcodes except for Data Matrix
I also tried to change the width and height when generating barcode but it made no difference whatsoever.