热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

java生成二维码实例

这篇文章主要介绍了java生成二维码的实例,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下

最近有点时间想学点东西,想做个简单的系统,现在登录的时候使用扫描二维码获取验证码登录,于是就有了下面的一些代码

首先要导入pom依赖

 
      com.google.zxing
      core
      3.3.0
 

这个是goole提供的一些包

第一个类是goole提供帮主类 画出图片

package com.cmbchina.ccd.itpm.baffle.util;
 
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import com.google.zxing.LuminanceSource;
 
public class BufferedImageLuminanceSource extends LuminanceSource {
 
  private final BufferedImage image;
  private final int left;
  private final int top;
 
  public BufferedImageLuminanceSource(BufferedImage image) {
    this(image, 0, 0, image.getWidth(), image.getHeight());
  }
 
  public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
    super(width, height);
 
    int sourceWidth = image.getWidth();
    int sourceHeight = image.getHeight();
    if (left + width > sourceWidth || top + height > sourceHeight) {
      throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
    }
 
    for (int y = top; y = getHeight()) {
      throw new IllegalArgumentException("Requested row is outside the image: " + y);
    }
    int width = getWidth();
    if (row == null || row.length 

生成图片工具类

package com.cmbchina.ccd.itpm.baffle.util;

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class QRCodeUtil {
  private static final String CHARSET = "utf-8";
  private static final String FORMAT_NAME = "JPG";
  // 二维码尺寸
  private static final int QRCODE_SIZE = 300;
  // LOGO宽度
  private static final int WIDTH = 60;
  // LOGO高度
  private static final int HEIGHT = 60;

  private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
    Hashtable hints = new Hashtable();
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
    hints.put(EncodeHintType.MARGIN, 1);
    BitMatrix bitMatrix =
        new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
    int width = bitMatrix.getWidth();
    int height = bitMatrix.getHeight();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    for (int x = 0; x  WIDTH) {
        width = WIDTH;
      }
      if (height > HEIGHT) {
        height = HEIGHT;
      }
      Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
      BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics g = tag.getGraphics();
      g.drawImage(image, 0, 0, null); // 绘制缩小后的图
      g.dispose();
      src = image;
    }
    // 插入LOGO
    Graphics2D graph = source.createGraphics();
    int x = (QRCODE_SIZE - width) / 2;
    int y = (QRCODE_SIZE - height) / 2;
    graph.drawImage(src, x, y, width, height, null);
    Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
    graph.setStroke(new BasicStroke(3f));
    graph.draw(shape);
    graph.dispose();
  }

  /**
   * @param content 编码到二维码中的内容
   * @param imgPath 要嵌入二维码的图片路径,如果不写或者为null则生成一个没有嵌入图片的纯净的二维码
   * @param destPath 生成的二维码的存放路径
   * @param needCompress true:表示将嵌入二维码的图片进行压缩,如果为“false”则表示不压缩
   * @param request
   * @param response 设置图片返回前端展示
   * @throws Exception
   */
  public static void encode(String content, String imgPath, String destPath, boolean needCompress,
               HttpServletRequest request, HttpServletResponse response) throws Exception {
    BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
    mkdirs(destPath);
    // String file = new Random().nextInt(99999999)+".jpg";
    // ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
    ImageIO.write(image, FORMAT_NAME, new File(destPath));
    response.setContentType("image/jpeg");
    // 设置响应头控制浏览器不要缓存
    response.setDateHeader("expries", -1);
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    ImageIO.write(image, FORMAT_NAME, response.getOutputStream());
  }

  public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {
    BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
    return image;
  }

  public static void mkdirs(String destPath) {
    File file = new File(destPath);
    // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
    if (!file.exists() && !file.isDirectory()) {
      file.mkdirs();
    }
  }

  public static void encode(String content, String imgPath, String destPath) throws Exception {
    QRCodeUtil.encode(content, imgPath, destPath, false);
  }
  // 被注释的方法
  /*
   * public static void encode(String content, String destPath, boolean
   * needCompress) throws Exception { QRCodeUtil.encode(content, null, destPath,
   * needCompress); }
   */

  public static void encode(String content, String destPath) throws Exception {
    QRCodeUtil.encode(content, null, destPath, false);
  }

  public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
      throws Exception {
    BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
    ImageIO.write(image, FORMAT_NAME, output);
  }

  public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
    BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
    mkdirs(destPath);
    // String file = new Random().nextInt(99999999)+".jpg";
    // ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
    ImageIO.write(image, FORMAT_NAME, new File(destPath));

  }

  public static void encode(String content, OutputStream output) throws Exception {
    QRCodeUtil.encode(content, null, output, false);
  }

  public static String decode(File file) throws Exception {
    BufferedImage image;
    image = ImageIO.read(file);
    if (image == null) {
      return null;
    }
    BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
    BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
    Result result;
    Hashtable hints = new Hashtable();
    hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
    result = new MultiFormatReader().decode(bitmap, hints);
    String resultStr = result.getText();
    return resultStr;
  }

  public static String decode(String path) throws Exception {
    return QRCodeUtil.decode(new File(path));
  }

}

controller

package com.cmbchina.ccd.itpm.baffle.controller;

import com.cmbchina.ccd.itpm.baffle.util.QRCodeUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Random;

/**
 * @Author zly
 * @Date 2020/6/24 15:54
 */
@RestController
@RequestMapping("image")
public class ImageController {
  @GetMapping("getImage")
  public void getImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String text = "http://101.132.36.16";
    // 嵌入二维码的图片路径
    String imgPath = "F:/qrCode/Koala.jpg";
    // 生成的二维码的路径及名称
    String destPath = "F:/qrCode/qrcode/jam.jpg";
    //这里可以根据业务逻辑产生二维码内容 这里我是使用随机数1000-9999
    int i = (int) (Math.random() * 9000 + 1000);
    
    //生成二维码并返回前端

    QRCodeUtil.encode("" + i, imgPath, destPath, true, request, response);

  }
}

二维码示例

以上就是java 生成二维码实例的详细内容,更多关于java 生成二维码的资料请关注其它相关文章!


推荐阅读
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 阿里Treebased Deep Match(TDM) 学习笔记及技术发展回顾
    本文介绍了阿里Treebased Deep Match(TDM)的学习笔记,同时回顾了工业界技术发展的几代演进。从基于统计的启发式规则方法到基于内积模型的向量检索方法,再到引入复杂深度学习模型的下一代匹配技术。文章详细解释了基于统计的启发式规则方法和基于内积模型的向量检索方法的原理和应用,并介绍了TDM的背景和优势。最后,文章提到了向量距离和基于向量聚类的索引结构对于加速匹配效率的作用。本文对于理解TDM的学习过程和了解匹配技术的发展具有重要意义。 ... [详细]
  • Linuxchmod目录权限命令图文详解在Linux文件系统模型中,每个文件都有一组9个权限位用来控制谁能够读写和执行该文件的内容。对于目录来说,执行位的作用是控制能否进入或者通过 ... [详细]
  • Skywalking系列博客1安装单机版 Skywalking的快速安装方法
    本文介绍了如何快速安装单机版的Skywalking,包括下载、环境需求和端口检查等步骤。同时提供了百度盘下载地址和查询端口是否被占用的命令。 ... [详细]
  • Lodop中特殊符号打印设计和预览样式不同的问题解析
    本文主要解析了在Lodop中使用特殊符号打印设计和预览样式不同的问题。由于调用的本机ie引擎版本可能不同,导致在不同浏览器下样式解析不同。同时,未指定文字字体和样式设置也会导致打印设计和预览的差异。文章提出了通过指定具体字体和样式来解决问题的方法,并强调了以打印预览和虚拟打印机测试为准。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • Final关键字的含义及用法详解
    本文详细介绍了Java中final关键字的含义和用法。final关键字可以修饰非抽象类、非抽象类成员方法和变量。final类不能被继承,final类中的方法默认是final的。final方法不能被子类的方法覆盖,但可以被继承。final成员变量表示常量,只能被赋值一次,赋值后值不再改变。文章还讨论了final类和final方法的应用场景,以及使用final方法的两个原因:锁定方法防止修改和提高执行效率。 ... [详细]
  • 本文介绍了求解gcdexgcd斐蜀定理的迭代法和递归法,并解释了exgcd的概念和应用。exgcd是指对于不完全为0的非负整数a和b,gcd(a,b)表示a和b的最大公约数,必然存在整数对x和y,使得gcd(a,b)=ax+by。此外,本文还给出了相应的代码示例。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • EPICS Archiver Appliance存储waveform记录的尝试及资源需求分析
    本文介绍了EPICS Archiver Appliance存储waveform记录的尝试过程,并分析了其所需的资源容量。通过解决错误提示和调整内存大小,成功存储了波形数据。然后,讨论了储存环逐束团信号的意义,以及通过记录多圈的束团信号进行参数分析的可能性。波形数据的存储需求巨大,每天需要近250G,一年需要90T。然而,储存环逐束团信号具有重要意义,可以揭示出每个束团的纵向振荡频率和模式。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • Microsoft Office for Mac最新版本安装教程,亲测可用!
    本文介绍了Microsoft Office for Mac最新版本的安装教程,经过亲测可用。Office工具是办公必备的工具,它为用户和企业设计,可以利用功能强大的Outlook处理电子邮件、日历和通讯录事宜。安装包包括Word、Excel、PPT、OneNote和Outlook。阅读本文可以了解如何下载并安装Office,以及安装过程中的注意事项。安装完毕后,可以正常使用Office中的Word等功能。 ... [详细]
  • 电销机器人作为一种人工智能技术载体,可以帮助企业提升电销效率并节省人工成本。然而,电销机器人市场缺乏统一的市场准入标准,产品品质良莠不齐。创业者在代理或购买电销机器人时应注意谨防用录音冒充真人语音通话以及宣传技术与实际效果不符的情况。选择电销机器人时需要考察公司资质和产品品质,尤其要关注语音识别率。 ... [详细]
author-avatar
手机用户2502892403
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有