ZXing库概述与平台支持
概述
ZXing作为一套开源的Java类库,支持对多种一维和二维条形码格式进行解析,其核心目标涵盖QR编码、Data Matrix以及UPC等一维条码的解码功能。该库兼容多平台客户端环境,包括J2ME、J2SE以及Android系统。
官方网站地址:[[wp:zxing官网]] GitHub仓库地址:[[wp:zxing github]]
实战应用
本案例旨在展示在非Android标准的Java开发环境中,如何利用ZXing库完成二维码图片的创建与数据读取操作。
环境安装
对于采用Maven构建的项目,只需在pom.xml中添加相应的依赖配置即可:
com.google.zxing
core
3.3.0
com.google.zxing
javase
3.3.0
若项目未使用Maven管理,可前往官方渠道下载发布版本包:[[wp:下载地址]]
二维码图片生成流程
利用ZXing生成二维码图片主要包含以下关键步骤:
首先,调用com.google.zxing.MultiFormatWriter类,依据传入的内容信息及图像编码参数,生成对应的二维图像矩阵(BitMatrix)。
其次,使用com.google.zxing.client.j2se.MatrixToImageWriter工具类,基于上述图像矩阵数据,将其写入为本地图片文件或转换为BufferedImage缓存对象。
public void encode(String content, String filepath) throws WriterException, IOException {
int width = 100;
int height = 100;
Map encodeHints = new HashMap();
encodeHints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, encodeHints);
Path path = FileSystems.getDefault().getPath(filepath);
MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
}
二维码图片解析流程
利用ZXing解析已有二维码图片需执行以下步骤:
第一步,通过javax.imageio.ImageIO读取指定的图片文件,并将其封装为java.awt.image.BufferedImage对象。
第二步,将该BufferedImage对象转换为ZXing能够识别处理的com.google.zxing.BinaryBitmap对象。
第三步,实例化com.google.zxing.MultiFormatReader,根据设定的图像解码参数对BinaryBitmap进行扫描解析。
public String decode(String filepath) throws IOException, NotFoundException {
BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap bitmap = new BinaryBitmap(binarizer);
HashMap decodeHints = new HashMap();
decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(bitmap, decodeHints);
return result.getText();
}
完整参考示例:[[wp:测试例代码]]
以下展示一个由程序生成的二维码图片样例:

以上内容即为本次分享的全部知识点,希望能对各位的学习工作有所助益,也欢迎持续关注本站获取更多技术资源。