介绍

  • 字符串封装成二维码,扫码就可以获取字符串内容。
  • 网址封装成二维码,扫码就可以跳转到对应网页。

快速开始

导入依赖

 <!--生成二维码--><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.3.0</version></dependency>

二维码生成工具类

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Hashtable;/*** 二维码生成工具类*/
public class QrCodeUtils {private static final String CHARSET = "utf-8";public static final String FORMAT = "JPG";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int LOGO_WIDTH = 60;// LOGO高度private static final int LOGO_HEIGHT = 60;/*** 生成二维码** @param content      二维码内容* @param logoPath     logo地址* @param needCompress 是否压缩logo* @return 图片*/public static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {Hashtable<EncodeHintType, Object> 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; x++) {for (int y = 0; y < height; y++) {image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);}}if (logoPath == null || "".equals(logoPath)) {return image;}// 插入图片QrCodeUtils.insertImage(image, logoPath, needCompress);return image;}/*** 插入LOGO** @param source       二维码图片* @param logoPath     LOGO图片地址* @param needCompress 是否压缩*/private static void insertImage(BufferedImage source, String logoPath,boolean needCompress) throws Exception {File file = new File(logoPath);if (!file.exists()) {System.err.println(""+logoPath+"   该文件不存在!");return;}Image src = ImageIO.read(new File(logoPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > LOGO_WIDTH) {width = LOGO_WIDTH;}if (height > LOGO_HEIGHT) {height = LOGO_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;}// 插入LOGOGraphics2D 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 logo图片地址(内嵌图片)* @param destPath 生成二维码存放地址* @param needCompress 是否压缩logo*/public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = QrCodeUtils.createImage(content, imgPath, needCompress);mkdirs(destPath);ImageIO.write(image, FORMAT, new File(destPath));}/*** 生成二维码(直接将二维码以图片输出流返回)** @param content 内容* @param imgPath logo图片地址(内嵌图片)* @param needCompress 是否压缩logo* @return 二维码图片*/public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {return QrCodeUtils.createImage(content, imgPath, needCompress);}/*** 创建多级文件* * @param destPath 目标目录*/public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}/*** 生成二维码(内嵌LOGO)** @param content      内容* @param logoPath     LOGO地址* @param output       输出流* @param needCompress 是否压缩LOGO*/public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)throws Exception {BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);ImageIO.write(image, FORMAT, output);}/*** 获取指定文件的输入流,获取logo** @param logoPath 文件的路径* @return 输入流*/public static InputStream getResourceAsStream(String logoPath) {return QrCodeUtils.class.getResourceAsStream(logoPath);}/*** 解析二维码** @param file 二维码图片* @return 解析结果*/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<DecodeHintType, Object> hints = new Hashtable<>();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);return result.getText();}/*** 解析二维码** @param path 二维码图片地址* @return 二维码解析结果*/public static String decode(String path) throws Exception {return QrCodeUtils.decode(new File(path));}
}

controller层

  • context:二维码里面的内容,如果字符串是网址,被扫描后则会跳转到对应网页
  • destPath:生成二维码图片的保存路径
  • logoPath:logo图片的路径
@ApiOperation(value = "获取二维码")
GetMapping("/qrCode")
public void qrCodeTest(HttpServletResponse response) throws Exception {// context是二维码里面的内容,如果是网址则会跳转到网址界面String context = "lixianhe";// 获取类路径下的logo文件ClassPathResource resource = new ClassPathResource("static/logo.jpg");//获logo.jpg的绝对路径String logoPath = resource.getFile().getPath();// String destPath = "D:\\qrCode\\csdn.jpg";QrCodeUtils.encode(context, logoPath, response.getOutputStream(), true);
}

logo.jpg是二维码的logo图片可以作为二维码的中心部分,该图片放在resources文件夹下。

获取resources文件下的内容

ClassPathResource resource = new ClassPathResource("static/logo.jpg");
//获logo.jpg的绝对路径(在target文件夹下)
String logoPath = resource.getFile().getPath();
// 输出logo.jpg文件的绝对路径
System.out.println(logoPath);

控制台输出

C:\Users\86131\Desktop\xxx\ManyDataSource\ManyDataSource\target\classes\static\logo.jpg

测试功能

访问接口,生成的二维码是以logo.jpg为中心的

扫码:可以查看到字符串 "lixianhe"

SpringBoot实现二维码生成相关推荐

  1. springboot使用imageio返回图片_SpringBoot 二维码生成(复制即用)

    二维码生成 基础环境 SpringBoot.Maven 代码 依赖 <!-- 工具类 import Controller import 效果 Base64 字符串 base64 转换为图片在线工 ...

  2. SpringBoot 二维码生成base64并上传OSS

    SpringBoot 二维码生成base64并上传OSS 基础环境 SpringBoot.Maven 代码实现 1.添加依赖 <!--二维码生成 --> <dependency> ...

  3. springBoot二维码生成案例

    1.首先引入谷歌开源项目依赖: <!-- 二维码支持包 --> <dependency><groupId>com.google.zxing</groupId& ...

  4. java 二维码生成和解析

    2019独角兽企业重金招聘Python工程师标准>>> <!-- 二维码 --><dependency><groupId>com.google.z ...

  5. zxing 二维码生成深度定制

    二维码生成服务之深度定制 之前写了一篇二维码服务定制的博文,现在则在之前的基础上,再进一步,花样的实现深度定制的需求,我们的目标是二维码上的一切都是可以由用户来随意指定 设计 1. 技术相关 zxin ...

  6. 舒工深度解析不规则场地座位二维码生成规则

    <!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8" ...

  7. 玩转Android之二维码生成与识别

    二维码,我们也称作QRCode,QR表示quick response即快速响应,在很多App中我们都能见到二维码的身影,最常见的莫过于微信了.那么今天我们就来看看怎么样在我们自己的App中集成二维码的 ...

  8. 支付宝支付 第五集:二维码生成工具

    支付宝支付 第五集:二维码生成工具 一.代码 目录结构 BufferedImageLuminanceSource.java package com.dzy.alipay.qrcode;import c ...

  9. Android之二维码生成与扫描

    转载请标明出处: http://blog.csdn.net/hai_qing_xu_kong/article/details/51260428 本文出自:[顾林海的博客] ##前言 月底离开公司,准备 ...

最新文章

  1. Excel、Exchange和C#
  2. shell用到的命令(2) —— break,continue,echo,eval,
  3. 深度学习中 batchnorm 层是咋回事?
  4. oracle 创建临时表报权限不足,ORACLE 临时表空间满了的原因解决方案
  5. 杨氏干涉的模拟的MATLAB仿真
  6. Python列表的用法和基本操作
  7. 杭州刚公布完摇号卖房新政,隔天就来个百亿地王,大家怎么看?
  8. 冒泡排序详解--python
  9. linux服务器程序乱码,Linux安装GBK/GB2312程序显示乱码的五种解决方法
  10. Hive中Map数据类型转String类型,其中具体内容不变
  11. MySQL错误:ERROR 1221 (HY000): Incorrect usage of UNION and ORDER BY
  12. $(...).modal is not a function
  13. CmemDC类 的使用方法
  14. Atitit 提升战力眼光和组织能力的几大要点 目录 1. 成长金字塔模型 德雷福斯模型 1 2. 提升战略眼光, 3 2.1. 视野与格局 3 2.2. 未来预测 未来发展负责,判断未来趋势, 3
  15. 高德地图根据关键词坐标拾取小工具
  16. 【Neo4j】第 1 章:图数据库
  17. rimworld简单机器人mod_rimworld分类技能机器人mod
  18. ANSYS APDL学习(5):ANSYS输入文件input file 的编写和调试方法
  19. OCP认证的优势是什么
  20. python 桌面程序自动化测试_对Windows桌面应用程序进行UI自动化测试

热门文章

  1. 3D 游戏之父卡马克再创业:“我自己出得起 2000 万美元,但花投资人的钱会更有责任心”...
  2. java编写程序实现乐手弹奏乐器。乐手可以弹奏不同的乐器从而发出不同的声音。可以弹奏的乐器包括二胡、钢琴和琵琶。定义乐器类Instrument,包括方法makeSound() 。定义乐器类的子类
  3. 文末送书 | 手把手教你玩转,Python 会交互的超强绘图库 Plotly!
  4. 敏捷式Mybatis
  5. 这个世界有病,我们都有病
  6. .net core npoi word文字下划线
  7. 夜天之书 #78 共建的神话
  8. 有什么PDF阅读器?告诉你三个好用的PDF阅读软件
  9. 【LeetCode】Day51-打家劫舍 III变形
  10. WORD页码相同问题