Zxing二维码生成

先导入core-3.3.0.jar。依赖

生成二维码方法。

implementation 'com.google.zxing:zxing-parent:3.3.3'
/***
 * 生成二维码
 *
 */

public static Bitmap generateBitmap(Context context, String content, int width, int height) {
    if ("".equals(content) || null == content) {
        Toast.makeText(context, context.getString(R.string.QrCode_load_faild), Toast.LENGTH_SHORT).show();
        return null;
    }
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    Map<EncodeHintType, String> hints = new HashMap<>();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    //设置空白边距的宽度
    hints.put(EncodeHintType.MARGIN, String.valueOf(2));

    try {
        BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        int[] pixels = new int[width * height];
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                if (encode.get(j, i)) {
                    pixels[i * width + j] = 0x00000000;
                } else {
                    pixels[i * width + j] = 0xffffffff;
                }
            }
        }
        return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
    } catch (WriterException e) {
        e.printStackTrace();
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/weixin_42493749/article/details/81180541