在页面设置一个“生成二维码”按钮,点击按钮,调用后台生成一个二维码图片,直接在浏览器下载下来。

生成二维码工具类QRCodeUtil.java:这个工具类需要导入依赖

<!--二维码依赖-->
<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.1.0</version>
</dependency>
package com.dosion.core.common.utils;import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;public class QRCode {private static final int BLACK = 0xFF000000;private static final int WHITE = 0xFFFFFFFF;//生成二维码public static String createQrCode(String url, String path, String fileName) {try {Map<EncodeHintType, String> hints = new HashMap<>();hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);File file = new File(path, fileName);if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {writeToFile(bitMatrix, "jpg", file);System.out.println("搞定:" + file);}} catch (Exception e) {e.printStackTrace();}return null;}//下载二维码public static void downFile(String url, String fileName, HttpServletRequest request, HttpServletResponse response) {try {//1.定义ContentType为("multipart/form-data")让浏览器自己解析文件格式response.setContentType("multipart/form-data");//2.中文名转码//response.setHeader("Content-disposition", "attachment; filename=\""+encodeChineseDownloadFileName(request, fileName+".xlsx") +"\"");response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));//获得文件File file = new File(url+fileName);FileInputStream in = new FileInputStream(file);//3.将文件写入缓冲区OutputStream(out)OutputStream out = new BufferedOutputStream(response.getOutputStream());int b = 0;byte[] buffer = new byte[2048];while ((b=in.read(buffer)) != -1){//4.将缓冲区文件输出到客户端(out)out.write(buffer,0,b);}in.close();out.flush();out.close();} catch (IOException e) {e.printStackTrace();}}//生成带图二维码public static void MatrixToImage(BitMatrix matrix,String format,String path, String fileName) throws IOException{File f = new File(path, fileName);//将我们的logo提取出来,建议这里单独写一个方法,我只是为了方便BufferedImage b = ImageIO.read(new File("e:/1.jpg"));//将logo弄成70*70,如果想大点,记得要提高我们二维码的容错率Image image = b.getScaledInstance(70, 70,Image.SCALE_FAST);BufferedImage bi = toBufferedImage(matrix);//获取二维码画刷Graphics g=bi.getGraphics();//定位g.drawImage(image ,165,165, null);//二维码画到相应文件位置,结束。if(ImageIO.write(bi, format, f)){}System.out.println("二维码生成成功!");}private static BufferedImage toBufferedImage(BitMatrix matrix){BufferedImage bi=new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB);for(int i=0;i<matrix.getWidth();i++){for(int j=0;j<matrix.getHeight();j++){//有值的是黑色,没有值是白色bi.setRGB(i, j,matrix.get(i, j)?BLACK:WHITE);}}return bi;}static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {BufferedImage image = toBufferedImage(matrix);if (!ImageIO.write(image, format, file)) {throw new IOException("Could not write an image of format " + format + " to " + file);}}static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {BufferedImage image = toBufferedImage(matrix);if (!ImageIO.write(image, format, stream)) {throw new IOException("Could not write an image of format " + format);}}private BufferedImage image;private int imageWidth = 450;  //图片的宽度private int imageHeight = 530; //图片的高度public void createImage(String fileLocation) {BufferedOutputStream bos = null;if(image != null){try {FileOutputStream fos = new FileOutputStream(fileLocation);bos = new BufferedOutputStream(fos);JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);encoder.encode(image);bos.close();} catch (Exception e) {e.printStackTrace();}finally{if(bos!=null){//关闭输出流try {bos.close();} catch (IOException e) {e.printStackTrace();}}}}}public void graphicsGeneration(String insertUrl, String createUrl, String activeName, String schoolName, String utitle) {int H_title = 100;     //头部高度int H_mainPic = 430;  //轮播广告高度image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);//设置图片的背景色Graphics2D main = image.createGraphics();main.setColor(Color.white);main.fillRect(0, 0, imageWidth, imageHeight);//***********************页面头部Graphics title = image.createGraphics();//设置区域颜色title.setColor(new Color(86, 171, 228));//填充区域并确定区域大小位置title.fillRect(0, 0, imageWidth, H_title);//设置字体颜色,先设置颜色,再填充内容title.setColor(Color.white);//设置字体Font titleFont = new Font("微软雅黑", Font.BOLD, 18);title.setFont(titleFont);title.drawString(activeName, 150, (H_title)/2-20);title.drawString(schoolName, 150, (H_title)/2-20+25);title.drawString(utitle, 150, (H_title)/2-20+50);//***********************插入二维码Graphics mainPic = image.getGraphics();BufferedImage bimg = null;try {bimg = ImageIO.read(new File(insertUrl));} catch (Exception e) {}if(bimg!=null){mainPic.drawImage(bimg, 0, H_title, imageWidth, H_mainPic, null);mainPic.dispose();}createImage(createUrl);}}

下载二维码工具类DownLoadUtil.java:

package com.dosion.core.common.utils.excel;import com.dosion.core.common.utils.StringUtils;
import org.springframework.core.io.DefaultResourceLoader;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;/*** 导出工具类* @author ty* @version 2019-2-13*/
public class DownLoadUtil {/*** * @Title: encodeChineseDownloadFileName * * @param @param request* @param @param pFileName* @param @return* @param @throws UnsupportedEncodingException* @return String* @throws*/public static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName)throws UnsupportedEncodingException {String filename = null;String agent = request.getHeader("USER-AGENT");if (null != agent) {if (-1 != agent.indexOf("Firefox")) {//Firefox  filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8")))) + "?=";} else if (-1 != agent.indexOf("Chrome")) {//Chrome  filename = new String(pFileName.getBytes(), "ISO8859-1");} else {//IE7+  filename = java.net.URLEncoder.encode(pFileName, "UTF-8");//替换特殊字符filename = StringUtils.replace(filename, "+", "%20");}} else {filename = pFileName;}return filename;}public static String getPysicalPath(String virtualPath,HttpServletRequest request) {//获得根绝对路径String physicalPath = getProjectPath();//获得项目路径String basePath = request.getContextPath();if(virtualPath.startsWith(basePath)){virtualPath = virtualPath.substring(basePath.length());}return physicalPath + virtualPath;}/*** @Title: downFile * @Description:* @param @param url文件url* @param @param fileName  文件名* @param @param response* @return void* @throws*/public static void downFile(String url,String fileName,HttpServletRequest request,HttpServletResponse response) {try {  //1.定义ContentType为("multipart/form-data")让浏览器自己解析文件格式  response.setContentType("multipart/form-data");  //2.中文名转码//response.setHeader("Content-disposition", "attachment; filename=\""+encodeChineseDownloadFileName(request, fileName+".xlsx") +"\"");response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx");//获得文件File file = new File(url);  FileInputStream in = new FileInputStream(file);  //3.将文件写入缓冲区OutputStream(out)  OutputStream out = new BufferedOutputStream(response.getOutputStream());  int b = 0;  byte[] buffer = new byte[2048];  while ((b=in.read(buffer)) != -1){//4.将缓冲区文件输出到客户端(out)out.write(buffer,0,b);}  in.close();out.flush(); out.close();  } catch (IOException e) { e.printStackTrace();}  }/*** 获取工程项目根路径* @return*/public static String getProjectPath(){// 如果配置了工程路径,则直接返回,否则自动获取。String projectPath = null;
//      if (StringUtils.isNotBlank(projectPath)){
//          return projectPath;
//      }try {File file = new DefaultResourceLoader().getResource("").getFile();if (file != null){while(true){File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");if (f == null || f.exists()){break;}if (file.getParentFile() != null){file = file.getParentFile();}else{break;}}projectPath = file.toString();}} catch (IOException e) {e.printStackTrace();}return projectPath;}
}

前台代码:

<button @click="GenerateQRcode(item.id)">生成二维码</button>
//生成二维码GenerateQRcode:function(classId){var url = api.user.generateClassQRCode;fetch(url,{method: 'POST',/*headers: new Headers({'token':dataUtils.getData(config.key.tokenKey) // 指定提交方式为表单提交}),*/}).then(res => res.blob().then(blob => {var a = document.createElement('a');var url = window.URL.createObjectURL(blob);var filename = 'rqcode.jpg';a.href = url;a.download = filename;a.click();window.URL.revokeObjectURL(url);}));},

后台代码:

 @ApiOperation("生成班级二维码")@RequestMapping(value = "generateClassQRCode", method = RequestMethod.POST)public void generateClassQRCode(String classId,HttpServletRequest request,HttpServletResponse response){//生成二维码
//要生成二维码的网址String url = "https://www.baidu.com/";
//指定生成路径String uploadPath = "/src/main/resources/temp/";String fileName = "QRcode";
//将虚拟路径转为物理路径String path = DownLoadUtil.getPysicalPath(uploadPath + fileName+"/", request);
//生成二维码QRCode.createQrCode(url,path,fileName+".jpg");//下载二维码QRCode.downFile(path,fileName+".jpg",request,response);}

后台二维码图片地址:

把成果贴这里:

在页面点击“生成二维码”,直接把二维码图片下载下来相关推荐

  1. 项目实践系列-点击生成自定义设置的二维码

    目前为止,生活中的我们到处可见一些二维码,使用微信扫一扫即可进入到另一个网络空间,这种方式方便了我们的生活,更让我们可以适应这种方式. 那么今天呢,我就个人项目经历,把点击生成自定义设置的二维码的一个 ...

  2. Android 点击生成二维码

    先看效果: 输入内容,点击生成二维码: 点击logo图案: 代码: QRCodeUtil: package com.example.administrator.zxing;import android ...

  3. 直播视频app源码,Android 点击生成二维码

    直播视频app源码,Android 点击生成二维码实现的相关代码 activity.xml代码如下: <?xml version="1.0" encoding="u ...

  4. 在web页面上快速生成二维码的三种实用方法

    转载自:在web页面上快速生成二维码的三种实用方法 二维码是桌面和移动端快速分享的高效手段之一,这里介绍两个不错的快速开发二维码的方法,和大家分享一下~~ 方法1:使用极客标签提供的二维码快速生成服务 ...

  5. 用二维码制作软件批量生成数据不定固定尺寸的二维码

    二维码的尺寸大小跟它包含的数据多少相关,具体尺寸可以在条码打印软件里设置.但是如果需要连接数据库批量生成二维码,而且二维码的数据时长短参差不齐的时候,二维码大小也会参差不齐.如果需要将数据不同的二维码 ...

  6. 生成二维码,扫描二维码,二维码预览三件套。uQRCode、uni.scanCode、uni.previewImage

    生成二维码,扫描二维码,二维码预览三件套.uQRCode.uni.scanCode.uni.previewImage 一.生成二维码 使用插件:uQRCode(在uniapp插件市场下载引入) 将uq ...

  7. 聚合支付二维码如何实现自动识别扫码客户端跳转相应支付页面

    前言 前面有一篇<聚合支付之流程概述>和大家聊了一下关于聚 合 支 付的一个简单流程.很多小伙伴私信我,如何实现聚合支付码的自动跳转呢? 其实,刚开始接触的时候我也很迷茫,一个静态的二维码 ...

  8. vue qrcodejs2生成二维码实现手机APP扫码进行web网页登录

    在vue中使用 qrcodejs2 1.安装 npm install  qrcodejs2 --save 2.引入 import QRCode from "qrcodejs2" 3 ...

  9. 二维码(生成二维码和扫描二维码)超简单 超简易

    二维码(生成二维码和扫描二维码)Zxing 例: 配置权限: 项目下的 build.gradle 文件里加入,7.0版本以后可能会转入settings.gradle文件 pluginManagemen ...

最新文章

  1. Android的API与差异化之路
  2. 微信小程序直播开启公测了,与平台直播有何不同?小程序直播如何搭建
  3. bazel 链接第三方动态库_Linux 动态库与静态库制作及使用详解
  4. 【转载】设置Windows中gvim的默认配色方案和字体
  5. Android中APK直接通过JNI访问驱动
  6. SAP UI5 jQuery.sap.setObject
  7. Oracle常见的Hint(二)
  8. oa导入表格html,oa系统表单模板导入操作过程
  9. CSDN看不见博主博客的评论_解决办法(亲测有效奥)
  10. 主力吸筹猛攻指标源码_通达信大于9000手大单指标公式,主力吸筹猛攻指标源码...
  11. CDA LEVELⅠ2021最新模拟题一(全网最详细有答案)
  12. git与gitlab使用教程
  13. VISIO同时选中多条线
  14. 百度、腾讯、搜狐、360等产品职位笔试智力题分析
  15. 伪NMOS的基本特点
  16. 运维之DNS服务器Bind9配置解析和基础示例及附带命令
  17. oracle查询员工员工部门领导领导部门,oracle多表查询之经典面试题
  18. 根据ACR/EULAR 2010 标准定义RA放射学侵蚀病变
  19. 【open3d】显示kitti 点云数据和bbox
  20. 都市丽人荣获多项大奖情感营销触达消费者心流

热门文章

  1. poll?transport=longpollconnection...烦人的请求
  2. spring-boot 深入学习
  3. 第 2-3 课:迭代法计算定积分
  4. 折页损失函数代码实现
  5. 第37天学习——CSS
  6. 【转】软件测试面试题(一)
  7. Unity基础学习路线
  8. 华尔街英语宝典,架构师必备技能
  9. 线程三连鞭之“线程基础”
  10. 如何将腾讯视频下载的qlv文件导入PR中编辑