Java后台生成二维码

项目中有时候需要把一些文字信息转化为二维码,方便用户扫描。特别是一些网页链接,输出为二维码后,用户就不用在手工输入,微信扫描就可以

添加依赖

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

二维码生成实现

package com.tenmao.qrcode;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Paths;


public class QrCodeUtil {
    private static final QRCodeWriter QR_CODE_WRITER = new QRCodeWriter();

    /**
     * 生成二维码字节数组.
     */
    public static byte[] generateQrCode(String text, String format, int width, int height) {
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            BitMatrix bitMatrix = QR_CODE_WRITER.encode(text, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToStream(bitMatrix, format, os);
            return os.toByteArray();
        } catch (WriterException e) {
            throw new RuntimeException(String.format("fail to generate qr code:text[%s]", text), e);
        } catch (IOException e) {
            throw new RuntimeException(String.format("fail to writeToStream when generating qr code: text[%s]", text), e);
        }
    }

    /**
     * 保存二维码图片到文件系统.
     */
    public static void generateQrCodeAndSave(String text, String format, int width, int height, String path) {
        try {
            BitMatrix bitMatrix = QR_CODE_WRITER.encode(text, BarcodeFormat.QR_CODE, width, height);
            MatrixToImageWriter.writeToPath(bitMatrix, format, Paths.get(path));
        } catch (WriterException e) {
            throw new RuntimeException(String.format("fail to generate qr code:text[%s]", text), e);
        } catch (IOException e) {
            throw new RuntimeException(String.format("fail to writeToStream when generating qr code: text[%s]", text), e);
        }
    }
}

验证结果

  • 生成一张本地图片
package com.tenmao.qrcode;

public class QRCodeGenerator {
    private static final String QR_CODE_IMAGE_PATH = "./MyQRCode.png";

    public static void main(String[] args) {
        QrCodeUtil.generateQrCodeAndSave("This is my first QR Code", "png", 350, 350, QR_CODE_IMAGE_PATH);
    }
}
  • 二维码如下图

MyQRCode.png

参考

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券