Java 生成二维码实战

简介

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

实战

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

安装

maven项目只需引入依赖:

<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 。

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 。

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();
}

在这里插入图片描述

欢迎关注我的微信公众号「码农突围」,分享Python、Java、大数据、机器学习、人工智能等技术,关注码农技术提升•职场突围•思维跃迁,20万+码农成长充电第一站,陪有梦想的你一起成长

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值