Java生成二维码

Java生成二维码

private BufferedImage createAQRCode(String text, Graphics2D g2d, int width, int height) {
        // 设置二维码参数
        ErrorCorrectionLevel level = ErrorCorrectionLevel.L; // 容错级别
        java.util.Map<EncodeHintType, Object> hints = new java.util.HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, level);
        // 生成二维码

        BufferedImage newImage = new BufferedImage(150, 150, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g3d = newImage.createGraphics();
        QRCodeWriter writer = new QRCodeWriter();

        BitMatrix bitMatrix = writer.encode(text, com.google.zxing.BarcodeFormat.QR_CODE, 150, 150, hints);
// 创建一个空白图片
        g3d.setColor(Color.WHITE);
        g3d.fillRect(150, 150, 150, 150);
        // 绘制二维码
        g3d.setColor(Color.BLACK);
        for (int x = 0; x < 150; x++) {
            for (int y = 0; y < 150; y++) {
                if (bitMatrix.get(x, y)) {
                    g3d.fillRect(x, y, 1, 1);
                }
            }
        }
        g2d.drawImage(newImage, (width - newImage.getWidth()) / 2, (height - newImage.getHeight()) / 2 + 70, 200, 200, null);
        g3d.dispose();
        return newImage;
    }

20231118223141356-image

生成二维码很简单,如果在使用过程的时候建议输出到缓存流进行使用

THE END
喜欢就支持一下吧
点赞16 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容