前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ZXing 生成、解析二维码图片的小示例

ZXing 生成、解析二维码图片的小示例

作者头像
静默虚空
发布2018-01-05 15:55:00
2.1K0
发布2018-01-05 15:55:00
举报
文章被收录于专栏:静默虚空的博客

概述

ZXing 是一个开源 Java 类库用于解析多种格式的 1D/2D 条形码。目标是能够对QR编码、Data Matrix、UPC的1D条形码进行解码。 其提供了多种平台下的客户端包括:J2ME、J2SE和Android。

官网:ZXing github仓库

实战

本例演示如何在一个非 android 的 Java 项目中使用 ZXing 来生成、解析二维码图片。

安装

maven项目只需引入依赖:

代码语言:javascript
复制
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>core</artifactId>
  <version>3.3.0</version>
</dependency>
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>3.3.0</version>
</dependency>

如果非maven项目,就去官网下载发布版本:下载地址

生成二维码图片

ZXing 生成二维码图片有以下步骤:

  1. com.google.zxing.MultiFormatWriter 根据内容以及图像编码参数生成图像2D矩阵。
  2. com.google.zxing.client.j2se.MatrixToImageWriter 根据图像矩阵生成图片文件或图片缓存 BufferedImage
代码语言:javascript
复制
public void encode(String content, String filepath) throws WriterException, IOException {
    int width = 100;
    int height = 100;
    Map<EncodeHintType, Object> encodeHints = new HashMap<EncodeHintType, Object>();
    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 解析二维码图片有以下步骤:

  1. 使用 javax.imageio.ImageIO 读取图片文件,并存为一个 java.awt.image.BufferedImage 对象。
  2. java.awt.image.BufferedImage 转换为 ZXing 能识别的 com.google.zxing.BinaryBitmap 对象。
  3. com.google.zxing.MultiFormatReader 根据图像解码参数来解析 com.google.zxing.BinaryBitmap
代码语言:javascript
复制
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<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
    decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
    Result result = new MultiFormatReader().decode(bitmap, decodeHints);
    return result.getText();
}

完整参考示例:测试例代码

参考

ZXing github仓库

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017-01-17 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 实战
    • 安装
      • 生成二维码图片
        • 解析二维码图片
        • 参考
        相关产品与服务
        图像处理
        图像处理基于腾讯云深度学习等人工智能技术,提供综合性的图像优化处理服务,包括图像质量评估、图像清晰度增强、图像智能裁剪等。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档