当前位置: 首页 > news >正文

Java生产带文字、带边框的二维码

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 {// 生成二维码的BitMatrixBitMatrix bitMatrix = generateQRCode(textToEncode, qrCodeWidth, qrCodeHeight);// 将BitMatrix转换为BufferedImageBufferedImage 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 {// 生成二维码的BitMatrixBitMatrix bitMatrix = generateQRCode(name, qrCodeWidth, qrCodeHeight);// 将BitMatrix转换为BufferedImageBufferedImage 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生成,然后再去修改成我想要的效果,如果有侵权的地方,还请联系本人。
如果代码有异常,或者有其他疑惑、或有新思路的同学,可以评论区留言。

http://www.lryc.cn/news/586610.html

相关文章:

  • 牛客:HJ19 简单错误记录[华为机考][字符串]
  • 009 ST表:静态区间最值的极致优化
  • 面试现场:奇哥扮猪吃老虎,RocketMQ高级原理吊打面试官
  • MyBatis实现分页查询-苍穹外卖笔记
  • comfyUI-controlNet-线稿软边缘
  • python-enumrate函数
  • HarmonyOS从入门到精通:动画设计与实现之六 - 动画曲线与运动节奏控制
  • houdini 用 vellum 制作一个最简单的布料
  • 洛谷题解 | UVA1485 Permutation Counting
  • C++结构体数组应用
  • Spring Boot 中使用 Lombok 进行依赖注入的示例
  • 基于springboot+Vue的二手物品交易的设计与实现(免费分享)
  • 2025年亚太杯(中文赛项)数学建模B题【疾病的预测与大数据分析】原创论文讲解(含完整python代码)
  • jieba 库:中文分词的利器
  • JAVA--双亲委派机制
  • 【springcloud】快速搭建一套分布式服务springcloudalibaba(四)
  • 【一起来学AI大模型】RAG系统流程:查询→向量化→检索→生成
  • 【AI News | 20250711】每日AI进展
  • 【TOOL】ubuntu升级cmake版本
  • AI产品经理面试宝典第12天:AI产品经理的思维与转型路径面试题与答法
  • 功耗校准数据PowerProfile测试方法建议
  • 【深度剖析】致力“四个最”的君乐宝数字化转型(下篇:转型成效5-打造数字化生存能力探索可持续发展路径)
  • VUE3 el-table 主子表 显示
  • Transformer基础
  • Openpyxl:Python操作Excel的利器
  • Qt 多线程编程:单例任务队列的设计与实现
  • 五、深度学习——CNN
  • NW728NW733美光固态闪存NW745NW746
  • C语言32个关键字
  • 锁相环初探