How to generate a custom QR code in Android programmatically using ZXing Library?

Auro picture Auro · Feb 10, 2017 · Viewed 13.3k times · Source

I'm using Journeyapp's ZXing Android Embedded library for my android app and I can generate a simple QR code using the following piece of code

 private void init() {

        ImageView qrImageView = (ImageView) findViewById(R.id.qr_image_view);

        qrImageView.setImageBitmap(generateQRBitMap("a"));

    }

    private Bitmap generateQRBitMap(final String content) {

        Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();

        hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);

        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        try {
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 512, 512, hints);

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

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

            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {

                    bmp.setPixel(x , y, bitMatrix.get(x,y) ? Color.BLACK : Color.WHITE);
                }
            }

            return bmp;
        } catch (WriterException e) {
            e.printStackTrace();
        }

        return null;
    }

However, I want to be able to generate something as cool as the one given belowenter image description here

Now I know that I may have to write a custom encoder for that, but I really don't know where to begin. The BitMatrix class always creates a square QR code, but is there anything that I can use to create the odd shapes?

Answer

Hussain KMR Behestee picture Hussain KMR Behestee · Feb 26, 2020

I found this library QRGen using ZXing and very easy to use. Whatever, to design at your desire, you may add another image behind of this QR code's Image View.

Sample Code for Generating QR Code

Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);