Java 二维码生成和解析的简单实现(谷歌Google.zxing)

本文介绍如何使用ZXing库生成二维码及解析二维码的方法。通过具体步骤和示例代码展示了创建二维码图片的过程,并提供了读取和解析二维码内容的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.下载地址:

https://github.com/zxing/zxing/releases


2.开始解压zip做个jar包:

建一个新项目包

(1)core/src/main/java下com文件夹复制到项目src下

(2)javase/src/main/java/com文件夹复制到项目src下

导出做个如图的jar包

3.

(1)建一个新项目

(2)建一个lib文件夹

(3)把jar包拷贝进lib文件夹下导入:

(4)建一个CreateQRCode--controller类.

如下图:



CreateQRCode.java文件编写代码:

package code;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

//生成二维码
public class CreateQRCode {
	public static void main(String[] args) {

		int width=300;
		int height=300;
		//图片后缀
		String format="png";
        //携带信息的内容
		String content="123456789";
		
		//定义二维码参数:
		 ///CHARACTER_SET---字符集
		HashMap hints=new HashMap();
		hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//常用M
		hints.put(EncodeHintType.MARGIN,2);//9数字越大距离周边距离越大
		
		//生成它(内容,宽,高)
		try {
			BitMatrix bitMatrix=new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width, height, hints);
			Path file=new File("/Users/zhang/Desktop/code4.png").toPath();//输出到你的指定路径
			MatrixToImageWriter.writeToPath(bitMatrix, format, file);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
运行:
桌面将出现一张二维码图片


解析二维码:

	public static void read() throws IOException, NotFoundException {
		
		MultiFormatReader formatReader=new MultiFormatReader();
		//指定文件图片路径
		File file=new File("/Users/zhang/Desktop/code4.png");
		BufferedImage image=ImageIO.read(file);
		BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
		//参数
		//定义二维码参数:
		 ///CHARACTER_SET---字符集
		HashMap hints=new HashMap();
		hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
		//得到结果
		Result result=formatReader.decode(binaryBitmap,hints);
		//解析结果
		System.out.println("解析结果=="+result);
		System.out.println("二维码格式类型=="+result.getBarcodeFormat());
		System.out.println("文本内容=="+result.getText());
		
	}
打印结果:

解析结果==123456789

二维码格式类型==QR_CODE

文本内容==123456789





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值