Java 二维码工具类
小于 1 分钟
Java 二维码工具类
将字符串转化为 QrCode 图像流
Maven 依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.1</version>
</dependency>
Maps 工具类
请查看这篇 Map工具类
工具类
import cn.linkot.assetsana.core.Dict;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.awt.image.BufferedImage;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
/**
* 二维码工具类
*/
@Slf4j
public class Qrs {
private static final Map<EncodeHintType, Object> HINT_TABLE =
Maps.asTable(
new Dict<>(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L),
new Dict<>(EncodeHintType.CHARACTER_SET, "utf-8"),
new Dict<>(EncodeHintType.MARGIN, 1)
);
public static BufferedImage qrCode(String text, int size){
try{
QRCodeWriter writer = new QRCodeWriter();
BitMatrix matrix = writer.encode(text, BarcodeFormat.QR_CODE, size, size, HINT_TABLE);
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int w = 0; w < width; w++){
for (int h = 0; h < height; h++){
image.setRGB(w, h, matrix.get(w, h)? 0x000000 : 0xFFFFFF);
}
}
return image;
}catch (Exception ex){
log.error("QR 创建失败:");
ex.printStackTrace();
return null;
}
}
}