使用 zxing 生成二维码以及条形码

2024-06-03 15:36

本文主要是介绍使用 zxing 生成二维码以及条形码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

需求背景

前期在做项目的时候,有一个需求是说要生成一张条形码,并且呢将条形码插入到 excel 中去,但是之前一直没有搞过找个条形码或者是二维码,最后是做出来了,这里呢就先看看怎么生成,后面再抽时间来写写怎么实现条形码插入到 excel 中去。

开始搭建

引入对应的 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>

条形码生成与读取

这里呢,我就不赘述太多了,因为这个就是一个工具类,设置好对应的参数,执行指定的方法就可以了,比较简单,具体的生成代码以及读取条形码的代码如下:

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;public class BarCodeUtils {/*** generateCode 根据code生成相应的一维码** @param file   一维码目标文件* @param code   一维码内容* @param width  图片宽度* @param height 图片高度*/public static void generateCode(File file, String code, int width, int height) {//定义位图矩阵BitMatrixBitMatrix matrix = null;try {// 使用code_128格式进行编码生成100*25的条形码MultiFormatWriter writer = new MultiFormatWriter();Map<EncodeHintType, Object> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");//定义编码参数 这里可以设置条形码的格式matrix = writer.encode(code, BarcodeFormat.CODE_128, width, height, hints);//matrix = writer.encode(code,BarcodeFormat.EAN_13, width, height, hints);} catch (WriterException e) {e.printStackTrace();}//将位图矩阵BitMatrix保存为图片try (FileOutputStream outStream = new FileOutputStream(file)) {assert matrix != null;ImageIO.write(MatrixToImageWriter.toBufferedImage(matrix), "png", outStream);outStream.flush();} catch (Exception e) {e.printStackTrace();}}/*** readCode 读取一张一维码图片** @param file 一维码图片名字或者是文件路径*/public static void readCode(File file) {try {BufferedImage image = ImageIO.read(file);if (image == null) {return;}LuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Map<DecodeHintType, Object> hints = new HashMap<>();hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);Result result = new MultiFormatReader().decode(bitmap, hints);System.out.println("条形码内容: " + result.getText());} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) throws Exception {generateCode(new File("D:\\barcode.png"), "123456789012", 500, 250);readCode(new File("D:\\barcode.png"));}}

执行下:
执行结果
对应的文件:
对应的文件

二维码生成与读取

上面我们看了下条形码的生成与读取,那么我们来看下二维码怎么生成:

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;public class QRCodeUtils {//生成二维码public static void generateQRCode(String content, int width, int height, String filePath) throws Exception {String format = "png";Map<EncodeHintType, Object> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");   //设置编码hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); //设置容错等级hints.put(EncodeHintType.MARGIN, 1);    // 设置边距BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);QRCodeUtils.outputQRCode(bitMatrix, format, filePath);}private static void outputQRCode(BitMatrix matrix, String format, String filePath) throws Exception {MatrixToImageWriter.writeToPath(matrix, format, java.nio.file.Paths.get(filePath));}//读取二维码public static void readQrCode(File file) {MultiFormatReader reader = new MultiFormatReader();try {BufferedImage image = ImageIO.read(file);BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));Map<DecodeHintType, Object> hints = new HashMap<>();hints.put(DecodeHintType.CHARACTER_SET, "utf-8");//设置编码Result result = reader.decode(binaryBitmap, hints);System.out.println("解析结果:" + result.toString());System.out.println("二维码格式:" + result.getBarcodeFormat());System.out.println("二维码文本内容:" + result.getText());} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) throws Exception {String filePath = "D:\\qrcode.png";generateQRCode("https://www.baidu.com", 300, 300, filePath);readQrCode(new File(filePath));}}

执行下:
执行结果
对应的文件:
对应的二维码文件

支持的格式源码部分

我们可以点击看下源码 BarcodeFormat 类中支持的各种格式,这里是将所有的都给枚举出来了,大家需要用到的时候再具体查看吧

public enum BarcodeFormat {AZTEC,CODABAR,CODE_39,CODE_93,CODE_128,DATA_MATRIX,EAN_8,EAN_13,ITF,MAXICODE,PDF_417,QR_CODE,RSS_14,RSS_EXPANDED,UPC_A,UPC_E,UPC_EAN_EXTENSION;private BarcodeFormat() {}
}

这篇关于使用 zxing 生成二维码以及条形码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1027392

相关文章

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

在 Spring Boot 中使用 @Autowired和 @Bean注解的示例详解

《在SpringBoot中使用@Autowired和@Bean注解的示例详解》本文通过一个示例演示了如何在SpringBoot中使用@Autowired和@Bean注解进行依赖注入和Bean... 目录在 Spring Boot 中使用 @Autowired 和 @Bean 注解示例背景1. 定义 Stud

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

使用Python快速实现链接转word文档

《使用Python快速实现链接转word文档》这篇文章主要为大家详细介绍了如何使用Python快速实现链接转word文档功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 演示代码展示from newspaper import Articlefrom docx import

oracle DBMS_SQL.PARSE的使用方法和示例

《oracleDBMS_SQL.PARSE的使用方法和示例》DBMS_SQL是Oracle数据库中的一个强大包,用于动态构建和执行SQL语句,DBMS_SQL.PARSE过程解析SQL语句或PL/S... 目录语法示例注意事项DBMS_SQL 是 oracle 数据库中的一个强大包,它允许动态地构建和执行

SpringBoot中使用 ThreadLocal 进行多线程上下文管理及注意事项小结

《SpringBoot中使用ThreadLocal进行多线程上下文管理及注意事项小结》本文详细介绍了ThreadLocal的原理、使用场景和示例代码,并在SpringBoot中使用ThreadLo... 目录前言技术积累1.什么是 ThreadLocal2. ThreadLocal 的原理2.1 线程隔离2

Python itertools中accumulate函数用法及使用运用详细讲解

《Pythonitertools中accumulate函数用法及使用运用详细讲解》:本文主要介绍Python的itertools库中的accumulate函数,该函数可以计算累积和或通过指定函数... 目录1.1前言:1.2定义:1.3衍生用法:1.3Leetcode的实际运用:总结 1.1前言:本文将详