Java文字转二维码

引入Maven依赖

        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>

Java代码

public class Test {
    // 二维码需要使用到的颜色
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static void main(String[] args) {
        createQrCodeImg();
    }

    public static void createQrCodeImg() {
        try {
            String data = "http://www.baidu.com";
            Map<EncodeHintType, String> character = new HashMap<>();
            // 设置字符集
            character.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            // 设置二维码的四个参数:需要生成的字符串,类型设置为二维码,二维码宽度,二维码高度,字符串字符集
            BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(data, BarcodeFormat.QR_CODE, 500, 500, character);
            // 二维码像素,也就是上面设置的 500
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            // 创建二维码对象
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    // 按照上面定义好的二维码颜色编码生成二维码
                    image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
                }
            }
            // 1.生成Base64图片
            // 生成的二维码图片对象转 base64
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            // 设置图片的格式
            ImageIO.write(image, "png", stream);
            String base64Img = Base64.encode(stream.toByteArray());
            System.out.println(base64Img);

            // 2.直接输出二维码文件
            // 这样写是生成在桌面,如果需要在另外的路径直接把文件路径替换即可。
            String imgPath = FileSystemView.getFileSystemView().getHomeDirectory() + File.separator;
            // 生成的二维码名称
            String imgName = "QrCodeStr.jpg";
            // 创建文件对象
            File file = new File(imgPath, imgName);
            ImageIO.write(image, "jpg", file);
            System.out.println("文件地址:" + file);
        } catch (Exception e) {
            throw new RuntimeException("生成二维码失败");
        }
    }
}

  • 8
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值