public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_WIDTH = 160;
private static final int QRCODE_HEIGHT = 161;
/**
* 生成二维码图片
* @param url 扫描二维码跳转地址
* @return
* @throws Exception
*/
public static BufferedImage createImage(String url) throws Exception {
//使用线程安全的map
Map<EncodeHintType,Object> hints = new ConcurrentHashMap<>();
//设置编码的纠错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
//指定生成条形码时要使用的边距(以像素为单位)。
hints.put(EncodeHintType.MARGIN, 1);
//生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, QRCODE_WIDTH, QRCODE_HEIGHT,hints);
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) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}
}
- THE END -
最后修改:2024年2月18日
非特殊说明,本博所有文章均为博主原创。
如若转载,请注明出处:https://jiaheming.cn/2023/05/java%e7%94%9f%e6%88%90%e4%ba%8c%e7%bb%b4%e7%a0%81/

共有 0 条评论