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

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

生成二维码工具类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);
    }

后台二维码图片地址:

把成果贴这里:

 

猜你喜欢

转载自blog.csdn.net/goodStudy_H/article/details/87871140