1. 程式人生 > >QRCode生成二維碼並帶有logo圖片

QRCode生成二維碼並帶有logo圖片

最近專案需要生成帶logo的二維碼供前臺下載,在網上找了幾篇文章,整合了一下。

首先需要的是QRCode.jar,我專案是直接maven依賴

<!-- Qrcode二維碼 -->
<dependency> 
        <groupId>QRCode</groupId>  
        <artifactId>QRCode</artifactId>  
        <version>3.0</version> 
</dependency> 

獲取資訊通過ajax傳送給後臺進行接收處理

function printEwm(){

    var LCNAME = $("input[name=LCNAME]").val();
    var BJH = $("input[name=BJH]").val();
    var SX = $("input[name=SX]").val();
    var SQR = $("input[name=SQR]").val();
    var LXDH = $("input[name=LXDH]").val();
    var SFZHM = $("input[name=SFZHM]").val();
    var SQSJ = $("input[name=SQSJ]"
).val(); $.ajax({ type : 'POST', async : true, url : '/bpm/bmfw/printEwm', data : {"lcname":LCNAME, "bjh":BJH, "sx":SX, "sqr":SQR, "lxdh":LXDH, "sfzhm":SFZHM, "sqsj":SQSJ, }, success : function
(addr){
location.href = addr; }, error : function(){ console.log("失敗"); } }); }

處理這些資訊並通過genQrcode()方法傳入輸出路徑和資訊生成二維碼,返回一個路徑供前臺下載(專案需要。。)

@RequestMapping(value="bpm/bmfw/printEwm",method=RequestMethod.POST)
    public @ResponseBody String printEwm(@RequestParam("lcname") String lcname,@RequestParam("bjh") String bjh,@RequestParam("sx") String sx,
                @RequestParam("sqr") String sqr,@RequestParam("lxdh") String lxdh,@RequestParam("sfzhm") String sfzhm,@RequestParam("sqsj") String sqsj,
                HttpServletResponse response,HttpServletRequest request) throws UnsupportedEncodingException{

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String time = sdf.format(date);
        /*System.out.println(time);*/

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String picTime = sdf2.format(date);


        String url = "\n許可證號:"+bjh+"\n申請人/單位:"+sqr+"\n統一社會信用程式碼/身份證號碼:"+sfzhm+"\n許可事項:"+sx+"\n聯絡電話:"+lxdh+"\n發證機關:丁蜀鎮便民服務中心"+"\n申請時間:"+sqsj+"\n發證時間:"+time;
        String path = request.getSession().getServletContext().getRealPath("resources")+File.separator+"申請單資訊二維碼"+picTime+".jpg";

        try {
            genQrcode(url, path,response,request);
        } catch (IOException e) {

            e.printStackTrace();
        }
        System.out.println("二維碼生成完畢");

        String result = "bpm/bmfw/downloadEwm?fileName=";

        return result+URLEncoder.encode("申請單資訊二維碼"+picTime+".jpg", "utf-8");
    }

這是生成二維碼的具體實現,以及在二維碼中插入logo圖片

    /**
     * 生成二維碼
     * @param url 二維碼的url文字內容
     * @param path  要存放二維碼的路徑
     * @throws IOException
     */
    public  void genQrcode(String url,String path,HttpServletResponse response,HttpServletRequest request) throws IOException{
        Qrcode x=new Qrcode();  
        x.setQrcodeErrorCorrect('M');//糾錯等級(四種等級)  
        x.setQrcodeEncodeMode('B');//N代表數字,A代表a-Z,B代表其他字元  
        x.setQrcodeVersion(20);//版本  ,版本越大,容納的位元組數越多

        /*int width = 67 + 12 * (7 - 1);//設定二維碼的大小公式:67 + 12 * (version - 1)  
        int height = 67 + 12 * (7 - 1);  */

        int width = 300;//設定二維碼的大小公式:67 + 12 * (version - 1)  
        int height = 300;  

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
        Graphics2D gs = bufferedImage.createGraphics();  

        gs.setBackground(Color.WHITE);  
        gs.setColor(Color.BLACK);  
        gs.clearRect(0, 0, width, height);//清除畫板的內容  

        int pixoff = 2;//新增一個偏移量  

        byte[] d = url.getBytes("utf-8");  
        System.out.println(d.length);
        if (d.length>0 && d.length <500){  
            boolean[][] s = x.calQrcode(d);  

            for (int i=0;i<s.length;i++){  
            for (int j=0;j<s.length;j++){  
                if (s[j][i]) {  
                gs.fillRect(j*3 + pixoff,i*3 + pixoff,3,3);  
                }  
            }  
            }  
        }  

        //中間插入logo
        int width_4 = width / 4;  
        int width_8 = width_4 / 2;  
        int height_4 = height / 4;  
        int height_8 = height_4 / 2;  
        String logoPath = request.getSession().getServletContext().getRealPath("resources")+File.separator+"applogo.png";
        Image img = ImageIO.read(new File(logoPath));  
        gs.drawImage(img, width_4 + width_8, height_4 + height_8,width_4,height_4, null);  

        gs.dispose();  
        bufferedImage.flush();  

        ImageIO.write(bufferedImage, "png", new File(path));  
    }

以下是前臺發起請求下載二維碼圖片

@RequestMapping(value="bpm/bmfw/downloadEwm",method=RequestMethod.GET)
    public void downloadEwm(HttpServletResponse response,HttpServletRequest request,@RequestParam("fileName")String fileName){

        String p = request.getSession().getServletContext().getRealPath("resources")+File.separator+fileName;
        System.out.println("輸入路徑: "+p); 
        File file = new File(p);

        // 建立檔案輸入流
        try {

            //設定頭資訊,內容處理的方式,attachment以附件的形式開啟,就是進行下載,並設定下載檔案的命名
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(), "UTF-8"));

            FileInputStream is = new FileInputStream(file);
            // 響應輸出流
            ServletOutputStream out = response.getOutputStream();
            // 建立緩衝區
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            is.close();
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }

附上完整的Controller

package com.eazytec.bmfw.controller;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.utils.URLEncodedUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.eazytec.webapp.controller.BaseFormController;
import com.swetake.util.Qrcode;

@Controller
public class EwmController extends BaseFormController{

    @RequestMapping(value="bpm/bmfw/printEwm",method=RequestMethod.POST)
    public @ResponseBody String printEwm(@RequestParam("lcname") String lcname,@RequestParam("bjh") String bjh,@RequestParam("sx") String sx,
                @RequestParam("sqr") String sqr,@RequestParam("lxdh") String lxdh,@RequestParam("sfzhm") String sfzhm,@RequestParam("sqsj") String sqsj,
                HttpServletResponse response,HttpServletRequest request) throws UnsupportedEncodingException{

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String time = sdf.format(date);
        /*System.out.println(time);*/

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmssSS");
        String picTime = sdf2.format(date);


        String url = "\n許可證號:"+bjh+"\n申請人/單位:"+sqr+"\n統一社會信用程式碼/身份證號碼:"+sfzhm+"\n許可事項:"+sx+"\n聯絡電話:"+lxdh+"\n發證機關:丁蜀鎮便民服務中心"+"\n申請時間:"+sqsj+"\n發證時間:"+time;
        String path = request.getSession().getServletContext().getRealPath("resources")+File.separator+"申請單資訊二維碼"+picTime+".jpg";

        try {
            genQrcode(url, path,response,request);
        } catch (IOException e) {

            e.printStackTrace();
        }
        System.out.println("二維碼生成完畢");

        String result = "bpm/bmfw/downloadEwm?fileName=";

        return result+URLEncoder.encode("申請單資訊二維碼"+picTime+".jpg", "utf-8");
    }

    /**
     * 生成二維碼
     * @param url 二維碼的url文字內容
     * @param path  要存放二維碼的路徑
     * @throws IOException
     */
    public  void genQrcode(String url,String path,HttpServletResponse response,HttpServletRequest request) throws IOException{
        Qrcode x=new Qrcode();  
        x.setQrcodeErrorCorrect('M');//糾錯等級(四種等級)  
        x.setQrcodeEncodeMode('B');//N代表數字,A代表a-Z,B代表其他字元  
        x.setQrcodeVersion(20);//版本  ,版本越大,容納的位元組數越多

        /*int width = 67 + 12 * (7 - 1);//設定二維碼的大小公式:67 + 12 * (version - 1)  
        int height = 67 + 12 * (7 - 1);  */

        int width = 300;//設定二維碼的大小公式:67 + 12 * (version - 1)  
        int height = 300;  

        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);  
        Graphics2D gs = bufferedImage.createGraphics();  

        gs.setBackground(Color.WHITE);  
        gs.setColor(Color.BLACK);  
        gs.clearRect(0, 0, width, height);//清除畫板的內容  

        int pixoff = 2;//新增一個偏移量  

        byte[] d = url.getBytes("utf-8");  
        System.out.println(d.length);
        if (d.length>0 && d.length <500){  
            boolean[][] s = x.calQrcode(d);  

            for (int i=0;i<s.length;i++){  
            for (int j=0;j<s.length;j++){  
                if (s[j][i]) {  
                gs.fillRect(j*3 + pixoff,i*3 + pixoff,3,3);  
                }  
            }  
            }  
        }  

        //中間插入logo
        int width_4 = width / 4;  
        int width_8 = width_4 / 2;  
        int height_4 = height / 4;  
        int height_8 = height_4 / 2;  
        String logoPath = request.getSession().getServletContext().getRealPath("resources")+File.separator+"applogo.png";
        Image img = ImageIO.read(new File(logoPath));  
        gs.drawImage(img, width_4 + width_8, height_4 + height_8,width_4,height_4, null);  

        gs.dispose();  
        bufferedImage.flush();  

        ImageIO.write(bufferedImage, "png", new File(path));  
    }

    @RequestMapping(value="bpm/bmfw/downloadEwm",method=RequestMethod.GET)
    public void downloadEwm(HttpServletResponse response,HttpServletRequest request,@RequestParam("fileName")String fileName){

        String p = request.getSession().getServletContext().getRealPath("resources")+File.separator+fileName;
        System.out.println("輸入路徑: "+p); 
        File file = new File(p);

        // 建立檔案輸入流
        try {

            //設定頭資訊,內容處理的方式,attachment以附件的形式開啟,就是進行下載,並設定下載檔案的命名
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(), "UTF-8"));

            FileInputStream is = new FileInputStream(file);
            // 響應輸出流
            ServletOutputStream out = response.getOutputStream();
            // 建立緩衝區
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            is.close();
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }



}