Java后台生成二维码
2019-07-15 本文已影响100人
十毛tenmao
项目中有时候需要把一些文字信息转化为二维码,方便用户扫描。特别是一些网页链接,输出为二维码后,用户就不用在手工输入,微信扫描就可以
添加依赖
<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);
}
}
- 二维码如下图