Java生成二维码的工具类

工具类

    //生成二维码
    public Bitmap createQRCodeBitmap(String code_url) {
        // 用于设置QR二维码参数
        final Hashtable<EncodeHintType, Object> qrParam = new Hashtable<EncodeHintType, Object>();
        // 设置QR二维码的纠错级别――这里选择最高H级别
        qrParam.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 设置编码方式
        qrParam.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        // 设定二维码里面的内容
        //	final String content = content;

        // 生成QR二维码数据――这里只是得到一个由true和false组成的数组
        // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
        int QRCODE_SIZE = DensityUtil.dip2px(this, 360);
        try {
            final BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url,
                    BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, qrParam);

            // 开始利用二维码数据创建Bitmap图片,分别设为黑白两色
            final int w = bitMatrix.getWidth();
            final int h = bitMatrix.getHeight();
            final int[] data = new int[w * h];

            for (int y = 0; y < h; y++) {
                for (int x = 0; x < w; x++) {
                    if (bitMatrix.get(x, y))
                        //		data[y * w + x] = 0xff19b393;// 标题的颜色
                        data[y * w + x] = 0xff000000;
                    else
                        data[y * w + x] = -1;// -1 相当于0xffffffff 白色
                }
            }

            // 创建一张bitmap图片,采用最高的图片效果ARGB_8888
            final Bitmap bitmap = Bitmap.createBitmap(w, h,
                    Bitmap.Config.ARGB_8888);
            // 将上面的二维码颜色数组传入,生成图片颜色
            bitmap.setPixels(data, 0, w, 0, 0, w, h);
            return bitmap;
        } catch (final WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

用法

 @BindView(R.id.image_qr)
 ImageView image_qr;
Bitmap bitmap = createQRCodeBitmap("https://blog.csdn.net/weixin_44177244/article/details/108723749");

image_qr.setImageBitmap(bitmap);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值