为了账号安全,请及时绑定邮箱和手机立即绑定

Java 生成二维码实战

标签:
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();
}
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Python工程师
手记
粉丝
20
获赞与收藏
151

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消