Last active
May 23, 2025 12:29
-
-
Save amalalbert/63ca2b654721fb7cd401a08ad418656e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.annotation.OptIn | |
import androidx.camera.core.ExperimentalGetImage | |
import androidx.camera.core.ImageAnalysis | |
import androidx.camera.core.ImageProxy | |
import com.google.mlkit.vision.barcode.BarcodeScannerOptions | |
import com.google.mlkit.vision.barcode.BarcodeScanning | |
import com.google.mlkit.vision.barcode.common.Barcode | |
import com.google.mlkit.vision.common.InputImage | |
class QrCodeAnalyzer( | |
private val onQrCodeScanned: (Barcode) -> Unit, | |
private val onQrCodeScanFailed: (e:Exception) -> Unit | |
) : ImageAnalysis.Analyzer { | |
@OptIn(ExperimentalGetImage::class) | |
override fun analyze(imageProxy: ImageProxy) { | |
val options = BarcodeScannerOptions.Builder() | |
.setBarcodeFormats(Barcode.FORMAT_QR_CODE) | |
.build() | |
val scanner = BarcodeScanning.getClient(options) | |
val mediaImage = imageProxy.image | |
mediaImage?.let { | |
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees) | |
scanner.process(image) | |
.addOnSuccessListener { barcodes -> | |
if (barcodes.size > 0) { | |
onQrCodeScanned(barcodes.first()) | |
} | |
imageProxy.close() | |
} | |
.addOnFailureListener { exception -> | |
// Task failed with an exception | |
onQrCodeScanFailed(exception) | |
exception.printStackTrace() | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment