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

server/2024/10/21 17:16:14/

目录

需求背景

前期在做项目的时候,有一个需求是说要生成一张条形码,并且呢将条形码插入到 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>

条形码生成与读取

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

java">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"));}}

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

二维码生成与读取

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

java">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 类中支持的各种格式,这里是将所有的都给枚举出来了,大家需要用到的时候再具体查看吧

java">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() {}
}

http://www.ppmy.cn/server/47321.html

相关文章

【Go语言精进之路】构建高效Go程序:零值可用、使用复合字面值作为初值构造器

&#x1f525; 个人主页&#xff1a;空白诗 文章目录 引言一、深入理解并利用零值提升代码质量1.1 深入Go类型零值原理1.2 零值可用性的实践与优势1.2.1 切片(Slice)的零值与动态扩展1.2.2 Map的零值与安全访问1.2.3 函数参数与零值 二、使用复合字面值作为初值构造器2.1 结构体…

msi安装mysql8 启动失败,提示只有在任务处于完成状态(RanToCompletion、Faulted 或 Canceled)时才能释放它。

解决方案: 1.打开服务,找到安装的mysql 2. 右击&#xff0c;打开属性&#xff0c;进入【登录】选项卡&#xff0c;选择本地系统账户。 3. 点击确定-->应用 4.服务中选择开始服务 5.服务启动成功后,在安装步骤中继续点击执行

小学数学出题器-Word插件-大珩助手

Word大珩助手是一款功能丰富的Office Word插件&#xff0c;旨在提高用户在处理文档时的效率。它具有多种实用的功能&#xff0c;能够帮助用户轻松修改、优化和管理Word文件&#xff0c;从而打造出专业而精美的文档。 【新功能】小学数学出题器 1、实现了难度设定&#xff1b;…

Kubernetes集群Pod控制器

前言 在 K8s 集群中&#xff0c;Pod 控制器是一种关键的组件&#xff0c;负责管理和控制Pod的生命周期。Pod 是 K8s 中最小的可部署单元&#xff0c;通常包含一个或多个容器&#xff0c;Pod 控制器则确保所需数量的 Pod 实例处于运行状态&#xff0c;并根据定义的规则进行自动…

MySQL表的增删改查初阶(上篇)

本篇会加入个人的所谓鱼式疯言 ❤️❤️❤️鱼式疯言:❤️❤️❤️此疯言非彼疯言 而是理解过并总结出来通俗易懂的大白话, 小编会尽可能的在每个概念后插入鱼式疯言,帮助大家理解的. &#x1f92d;&#x1f92d;&#x1f92d;可能说的不是那么严谨.但小编初心是能让更多人…

【R基础】如何开始学习R-从下载R及Rstudio开始

文章目录 概要下载R流程下载Rstudio流程下载完成-打开 概要 提示&#xff1a;如何开始学习R-从下载R及Rstudio开始&#xff0c;此处我只是想下载指定版本R4.3.3 下载R流程 链接: R官网 文件下载到本地 下载文件展示 按照向导指示安装 下载Rstudio流程 链接: Rstudio官网…

Ubuntu server 24 (Linux) 安装部署smartdns 搭建智能DNS服务器

SmartDNS是推荐本地运行的DNS服务器&#xff0c;SmartDNS接受本地客户端的DNS查询请求&#xff0c;从多个上游DNS服务器获取DNS查询结果&#xff0c;并将访问速度最快的结果返回给客户端&#xff0c;提高网络访问速度和准确性。 支持指定域名IP地址&#xff0c;达到禁止过滤的效…

成功解决“ModuleNotFoundError: No Module Named ‘utils’”错误的全面指南

成功解决“ModuleNotFoundError: No Module Named ‘utils’”错误的全面指南 在Python编程中&#xff0c;遇到ModuleNotFoundError: No Module Named utils这样的错误通常意味着Python解释器无法找到名为utils的模块。这可能是由于多种原因造成的&#xff0c;比如模块确实不存…