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

编程入门 行业动态 更新时间:2024-10-28 14:24:53

在页面点击“生成<a href=https://www.elefans.com/category/jswz/34/1768147.html style=二维码”,直接把二维码图片下载下来"/>

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

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

生成二维码工具类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 = "/";
//指定生成路径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);}

后台二维码图片地址:

把成果贴这里:

 

更多推荐

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

本文发布于:2023-06-23 16:37:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/851781.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:二维码   图片下载   页面

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!