Java 生成带文字、带边框的二维码
- 1、Java 生成带文字的二维码
-
- 1.1、导入jar包
- 1.2、普通单一的二维码
-
- 1.2.1、代码示例
- 1.2.2、效果
- 1.3、带文字的二维码
-
- 1.3.1、代码示例
- 1.3.2、效果
- 2、带边框的二维码
-
- 2.1、代码示例
- 2.2、带边框的二维码效果
1、Java 生成带文字的二维码
在做一些标签时,我们时常会用到二维码,现在我们利用Java来生成二维码。
1.1、导入jar包
在pom.xml中,导入zxing包
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
1.2、普通单一的二维码
1.2.1、代码示例
rHeight = 100; // 二维码核心区域高度(不含边距)
int margin = 50; // 边距大小(像素)
// 生成二维码(无边距)
BitMatrix bitMatrix = new MultiFormatWriter().encode(
content, BarcodeFormat.QR_CODE, qrWidth, qrHeight
);
BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
// 创建带边距的画布
int totalWidth = qrWidth ;
int totalHeight = qrHeight ;
BufferedImage finalImage = new BufferedImage(
totalWidth, totalHeight, BufferedImage.TYPE_INT_RGB
);
Graphics2D graphics = finalImage.createGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, totalWidth, totalHeight); // 填充背景
// 将二维码绘制到画布中央(可调整位置)
graphics.drawImage(qrImage, 0, 0, null);
graphics.dispose();
// 保存图像
ImageIO.write(finalImage, "PNG", new File("测试.png"));
}
1.2.2、效果
1.3、带文字的二维码
1.3.1、代码示例
/**
* 二维码属性设置
* @param text 内容
* @param width 宽度
* @param height 高度
* @return
* @throws WriterException
*/
private static BitMatrix generateQRCode(String text, int width, int height) throws WriterException {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //字符集
// hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容错率
hints.put(EncodeHintType.MARGIN, 0);// 禁用ZXing默认边距
return new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
}
//二维码图上带字
public static void contextLoads(String name,String path) {
String textToEncode = name;
int qrCodeWidth = 100;
int qrCodeHeight = 100;
int textPadding = 10; // 文本与二维码之间的间距
int textSize = 10; // 文本字体大小
int totalHeight = qrCodeHeight + textPadding;
try {
// 生成二维码的BitMatrix
BitMatrix bitMatrix = generateQRCode(textToEncode, qrCodeWidth, qrCodeHeight);
// 将BitMatrix转换为BufferedImage
BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
// 创建一个新的BufferedImage来容纳二维码和文本
BufferedImage combinedImage = new BufferedImage(
qrCodeWidth, totalHeight, BufferedImage.TYPE_INT_RGB);
// 绘制二维码到新的BufferedImage上
Graphics2D g2d = combinedImage.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, qrCodeWidth, totalHeight);
g2d.drawImage(qrCodeImage, 0, 0, null);
// 设置文本样式
Font font = new Font("Arial", Font.PLAIN, textSize);
g2d.setFont(font);
g2d.setColor(Color.BLACK); // 文本颜色
// 绘制文本到图片下方
FontMetrics metrics = g2d.getFontMetrics();
int textX = (qrCodeWidth - metrics.stringWidth(textToEncode)) / 2;
int textY = qrCodeHeight + textPadding;
g2d.drawString(textToEncode, textX, textY);
g2d.dispose();
// 指定存储图片的路径
Path filePath = Paths.get(path+name+".png");
// 确保文件路径的父目录存在
filePath.getParent().toFile().mkdirs();
// 保存图片到文件
ImageIO.write(combinedImage, "PNG", filePath.toFile());
System.out.println("QR Code with text has been generated: " + filePath.toAbsolutePath());
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// 指定存储二维码图片的路径
String filePath = "D:/data/";
contextLoads("C40851-WZ-A01",filePath);
}
1.3.2、效果
2、带边框的二维码
因为我将生成的二维码图片导出到excel表格的时候,二维码图片覆盖了excel表格的边框,显得很突兀,所以我考虑将二维码图片加个边框,在导出的时候,二维码边框可以替代excel边框。
2.1、代码示例
我们在带文字的二维码生成类里面新增一些内容,并更详细的增加了一些注释。
/**
* 二维码属性设置
* @param text 内容
* @param width 宽度
* @param height 高度
* @return
* @throws WriterException
*/
private static BitMatrix generateQRCode(String text, int width, int height) throws WriterException {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); //字符集
//默认边距是为了二维码能更好的识别,如果禁用默认边距,为了能更好识别,最好要设置高容错率
// hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容错率
hints.put(EncodeHintType.MARGIN, 0);// 禁用ZXing默认边距 不禁用会有较多空白区域
return new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
}
/**
* 二维码图上带字
* @param name 二维码 生成的内容 和 二维码上的文字 及 二维码的名称
* @param path 二维码保存的路径
*/
public static void contextLoads2(String name,String path) {
int qrCodeWidth = 100; //二维码宽度
int qrCodeHeight = 100;//二维码高度
int textPadding = 10; // 文本与二维码之间的间距
int textSize = 10; // 文本字体大小
int borderWidth=1;//边框大小
int totalHeight = qrCodeHeight + textPadding;//总高度 加上文本二维码之间的间距
try {
// 生成二维码的BitMatrix
BitMatrix bitMatrix = generateQRCode(name, qrCodeWidth, qrCodeHeight);
// 将BitMatrix转换为BufferedImage
BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
// 3. 创建带边框的图像
int borderedSize = totalHeight + 2 * borderWidth;
//因为borderedSize 包含了textPadding
// 所以把宽度设置为borderedSize时,两边空白太多了,所以减掉了
BufferedImage image = new BufferedImage(
borderedSize-textPadding,
borderedSize,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = image.createGraphics();
// 4. 绘制黑色边框
graphics.setColor(Color.BLACK);
// 起始 x y 宽度 高度
graphics.fillRect(0, 0, borderedSize, borderedSize);
// 绘制二维码到新的BufferedImage上
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.WHITE);
// 起始 x y 宽度 高度
g2d.fillRect(borderWidth, borderWidth, qrCodeWidth, totalHeight);
g2d.drawImage(qrCodeImage, borderWidth, borderWidth, null);
// 设置文本样式
Font font = new Font("Arial", Font.PLAIN, textSize);
g2d.setFont(font);
g2d.setColor(Color.BLACK); // 文本颜色
// 绘制文本到图片下方
FontMetrics metrics = g2d.getFontMetrics();
// x 居中位置
int textX = (qrCodeWidth - metrics.stringWidth(name)) / 2 +borderWidth;
int textY = qrCodeHeight + textPadding;
g2d.drawString(name, textX, textY);
g2d.dispose();
// 指定存储图片的路径
Path filePath = Paths.get(path+name+".png");
// 确保文件路径的父目录存在
filePath.getParent().toFile().mkdirs();
// 保存图片到文件
ImageIO.write(image, "PNG", filePath.toFile());
System.out.println("QR Code with text has been generated: " + filePath.toAbsolutePath());
} catch (WriterException | IOException e) {
e.printStackTrace();
}
}
2.2、带边框的二维码效果
以上就是本文的全部内容,部分代码是利用AI生成,然后再去修改成我想要的效果,如果有侵权的地方,还请联系本人。
如果代码有异常,或者有其他疑惑、或有新思路的同学,可以评论区留言。