Create a QR code and show it in ImageView

I am creating an application that can scan a QR code and create a QR code. The scanning part is completed and is working properly. But when I try to create a QR code and show it in ImageView, the created QR code does not contain the correct text. I am using the ZXING library.

Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

QRCodeWriter qrCodeEncoder = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeEncoder.encode(myText, BarcodeFormat.QR_CODE,
        200, 200, hintMap);

height = bitMatrix.getHeight();
width = bitMatrix.getWidth();

final Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

for (x = 0; x < width; x++){
    bmp.setPixel(x, y, bitMatrix.get(x,y) ? Color.BLACK : Color.WHITE);
}

ImageView myImage = (ImageView) findViewById(R.id.qr_code);
myImage.setImageBitmap(bmp);
+4
source share
2 answers

Error in the for loop. You missed the inner loop. But why did you get an empty image?

Use the snippet below.

for (x = 0; x < width; x++){
    for (y = 0; y < height; y++){
        bmp.setPixel(x, y, bitMatrix.get(x,y) ? Color.BLACK : Color.WHITE);
    }
}

That should work.

+2
source

Try the full code:

    com.google.zxing.Writer writer = new QRCodeWriter();
    // String finaldata = Uri.encode(data, "utf-8");
    int width = 250;
    int height = 250;
    BitMatrix bm = writer
            .encode(data, BarcodeFormat.QR_CODE, width, height);
    Bitmap ImageBitmap = Bitmap.createBitmap(width, height,
            Config.ARGB_8888);

    for (int i = 0; i < width; i++) {// width
        for (int j = 0; j < height; j++) {// height
            ImageBitmap.setPixel(i, j, bm.get(i, j) ? Color.BLACK
                    : Color.WHITE);
        }
    }

Works!

+2
source

All Articles