栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

基于google zxing的Java二维码生成与解码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于google zxing的Java二维码生成与解码

 本文实例为大家分享了Java二维码生成与解码的具体代码,供大家参考,具体内容如下

一、添加Maven依赖(解码时需要上传二维码图片,所以需要依赖文件上传包)



 com.google.zxing
 javase
 3.1.0




 commons-fileupload
 commons-fileupload
 1.3.1


 commons-io
 commons-io
 2.4


二、创建生成二维码接口(接口参数为二维码内容,通常是URL)


@RequestMapping(value = "/qrcode/encode", method = RequestMethod.POST)
public void encodeQrCode(String text, HttpServletResponse response) {
  try {
   // 设置二维码参数
   Map hints = new HashMap();
   hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
   BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 150, 150, hints);
   //返回二维码
   MatrixToImageWriter.writeToStream(bitMatrix, "jpg", response.getOutputStream());
  } catch (Exception e) {
   e.printStackTrace();
  }
}

三、创建二维码解码接口(直接返回解码后的二维码内容)


@RequestMapping(value = "/qrcode/decode", method = RequestMethod.POST)
public String decodeQrCode(MultipartFile qrImg) {
  if (!qrImg.isEmpty()) {
   try {
     BufferedImage image = ImageIO.read(qrImg.getInputStream());

     BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));

     // 定义二维码的参数:
     HashMap hints = new HashMap<>();
     // 定义字符集
     hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

     Result result = new MultiFormatReader().decode(binaryBitmap, hints);

     return result.getText();
   } catch (Exception e) {
     e.printStackTrace();
   }
  }

  return null;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/145143.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号