Creating colored QR codes using zxing

痞子三分冷 提交于 2019-12-04 16:26:04

In MatrixToImageWriter.java (which I assume you are using), under javase/ change the constant BLACK. It is an int in ARGB format and currently has value 0xFF000000. Leave the alpha value at 0xFF. Change the rest to describe your color in hex format. You can do the same with WHITE if you like.

Try this ::

BitMatrix matrix = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, this.width, this.height, getEncodeHints());
/*
Here the config object represents the QR Code colors.
i.e. Brown and White respectively
*/ 
MatrixToImageConfig conf = new MatrixToImageConfig(-10223615,-1);
BufferedImage qrcode = MatrixToImageWriter.toBufferedImage(matrix, conf);

I assume that you're generating qr code like below:

QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(code,null,
                                                Contents.Type.TEXT,
                                                BarcodeFormat.QR_CODE.toString(),            
                                                yourDimension);

Your output's dimension will be based on your code. Set your dimension as possible as low. So you can find exact positions of qr code place you want to change color.

Than get your pixels from bitmap with:

int[] allpixels = new int[bitmap.getHeight() * bitmap.getWidth()];
bitmap.getPixels(allpixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

And color pixels you want:

for (int i = 6; i < 9; i++) {
     allpixels[i] = Color.Red; // your rgb color
      }

Convert dp to px for every devices:

qrCodeDimension = dpToPx((int) getResources().getDimension(R.dimen.qr_dimen));

public static int dpToPx(int dp) {
      return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
   }

Finaly set your colored pixels to bitmap:

bitmap.setPixels(allpixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

return Bitmap.createScaledBitmap(bitmap, qrCodeDimension, qrCodeDimension, false);

This's how i solved the problem. I hope this'll help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!