源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2020-04-13 04:09 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java中ZXing 生成、解析二维码图片的小示例
概述 ZXing 是一个开源 Java 类库用于解析多种格式的 1D/2D 条形码。目标是能够对QR编码、Data Matrix、UPC的1D条形码进行解码。 其提供了多种平台下的客户端包括:J2ME、J2SE和Android。 官网:[url=https://github.com/zxing/zxing]ZXing github仓库[/url] 实战 本例演示如何在一个非 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项目,就去官网下载发布版本:[url=https://github.com/zxing/zxing/releases]下载地址  [/url] [b]生成二维码图片[/b] 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);
}
[b]解析二维码图片[/b] 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();
}

完整参考示例:[url=http://xiazai.jb51.net/201701/yuanma/QRCodeUtilTest_jb51.rar]测试例代码 [/url] 以下是一个生成的二维码图片示例: [img]http://files.jb51.net/file_images/article/201701/2017117142446800.png?2017017142510[/img] 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部