journeyapps / zxing-android-embedded

Barcode scanner library for Android, based on the ZXing decoder
https://journeyapps.com/
Apache License 2.0
5.68k stars 1.26k forks source link

how to scan QR from gallery Image #734

Open Jaysinh001 opened 1 year ago

Jaysinh001 commented 1 year ago

I want to Scan QR code from Gallery but I don't know how to do it.... can any one help me

Below is my code to fetch Image from gallery .....

btnUploadFromGallery.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {

            Intent iGallery = new Intent(Intent.ACTION_PICK);
            iGallery.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(iGallery,200);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK){
        if (requestCode == 200){
            Uri ImageUri = data.getData();
            scannerView.setResultHandler((ZXingScannerView.ResultHandler) ImageUri);
        }
    }
}
angelix commented 11 months ago

This discussion can help you.

sachin-varshney commented 9 months ago
private val openGalleryRequest =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == AppCompatActivity.RESULT_OK) {
                it.data?.data?.let { uri -> decodeQRCode(uri) }
            }
        }

    private fun openGallery() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT
        openGalleryRequest.launch(Intent.createChooser(intent, "Scan Gallery"))
    }

    private fun decodeQRCode(imageUri: Uri) {
        try {
            val inputStream = context?.contentResolver?.openInputStream(imageUri)
            val bitmap = BitmapFactory.decodeStream(inputStream)

            val intArray = IntArray(bitmap.width * bitmap.height)
            bitmap.getPixels(intArray, 0, bitmap.width, 0, 0, bitmap.width, bitmap.height)

            val source: LuminanceSource = RGBLuminanceSource(bitmap.width, bitmap.height, intArray)
            val binaryBitmap = BinaryBitmap(HybridBinarizer(source))

            val reader = QRCodeReader()
            val result = reader.decode(binaryBitmap)

            // The QR code content is in result.text
            val qrCodeContent = result.text
            proceedQrData(qrCodeContent)

        } catch (e: Exception) {
            // Handle exceptions (e.g., QR code not found)

        }
    }