1、首先导入需要使用的工具类
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>org.jodd</groupId>
<artifactId>jodd-core</artifactId>
<version>5.1.5</version> <!-- 根据你需要的版本进行修改 -->
</dependency>
2、设置二维码的参数格式
/**
* 设置二维码的格式参数
* @return
*/
private static Map<EncodeHintType, Object> getDecodeHintType() {
// 用于设置QR二维码参数
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 设置编码方式
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 0);
hints.put(EncodeHintType.MAX_SIZE, 350);
hints.put(EncodeHintType.MIN_SIZE, 100);
return hints;
}
3、生成二维码的具体方法
/**
* @Author: jiang5sx
* @Description: 生成普通的二维码
* @Date:
*/
public static BufferedImage createCode(String qrUrl) {
MultiFormatWriter multiFormatWriter = null;
BitMatrix bm = null;
BufferedImage image = null;
Map<EncodeHintType, Object> hints = getDecodeHintType();
try {
multiFormatWriter = new MultiFormatWriter();
// 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, width, height, hints);
int w = bm.getWidth();
int h = bm.getHeight();
image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
// 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGCOLOR);
}
}
} catch (WriterException e) {
e.printStackTrace();
}
return image;
}
4、调用并成功二维码
public class Test{
public static void main(String[] args) throws IOException {
//text要生成内容
String text = "https://blog.youkuaiyun.com/m0_48952989/article/details/128376479?spm=1001.2014.3001.5501";
BufferedImage bufferedImage = createCode(text);
String fileName = "qrcode.png";
//filePath 保存的路径
String filePath = "D:\\" + fileName;
File file = new File(filePath);
ImageIO.write(bufferedImage, "png", file);
}
}
5、运行结果
6、扩展:生成带log的二维码
/**
* @Author:jiang5sx
* @Description: 生成带logo的二维码
* @Date:
*/
public static BufferedImage createCodeWithLogo(String qrUrl, String logoPath) {
BufferedImage bim = createCode(qrUrl);
try {
// 读取二维码图片,并构建绘图对象
Graphics2D g = bim.createGraphics();
// 读取Logo图片
BufferedImage logo = ImageIO.read(new File(logoPath));
//设置logo的大小,这里设置为二维码图片的20%,过大会盖掉二维码
int widthLogo = Math.min(logo.getWidth(null), bim.getWidth() * 3 / 10),
heightLogo = logo.getHeight(null) > bim.getHeight() * 3 / 10 ? (bim.getHeight() * 3 / 10) : logo.getWidth(null);
// logo放在中心
int x = (bim.getWidth() - widthLogo) / 2;
int y = (bim.getHeight() - heightLogo) / 2;
// logo放在右下角
// int x = (image.getWidth() - widthLogo);
// int y = (image.getHeight() - heightLogo);
//开始绘制图片
g.drawImage(logo, x, y, widthLogo, heightLogo, null);
g.dispose();
logo.flush();
bim.flush();
return bim;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
7、运行结果