1. 程式人生 > >java生成二維碼(java工具類可以直接呼叫)

java生成二維碼(java工具類可以直接呼叫)

生成二維碼的方法大體分為兩種:1. 展示時候引用Qrcode.js;2.後臺生成二維碼儲存成圖片,前端顯示

1.QRCode.js 是一個用於生成二維碼的 JavaScript 庫。主要是通過獲取 DOM 的標籤,再通過 HTML5 Canvas 繪製而成

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">
<head>
<title>Javascript 二維碼生成庫:QRCode</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://static.runoob.com/assets/qrcode/qrcode.min.js"></script>
</head>
<body>
<input id="text" type="text" value="http://www.runoob.com" style="width:80%" /><br />
<div id="qrcode" style="width:100px; height:100px; margin-top:15px;"></div>

<script type="text/javascript">
var qrcode = new QRCode(document.getElementById("qrcode"), {
	width : 100,
	height : 100
});

function makeCode () {		
	var elText = document.getElementById("text");
	
	if (!elText.value) {
		alert("Input a text");
		elText.focus();
		return;
	}
	
	qrcode.makeCode(elText.value);
}

makeCode();

$("#text").
	on("blur", function () {
		makeCode();
	}).
	on("keydown", function (e) {
		if (e.keyCode == 13) {
			makeCode();
		}
	});
</script>
</body>
</html>
標題

2.後臺生成二維碼

必不可少的maven依賴
<!-- 條形碼、二維碼生成  -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.2.1</version>
</dependency>
package com.thinkgem.jeesite.common.qrcode;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
 * 二維碼 新增 logo圖示 處理的方法,
 * 模仿微信自動生成二維碼效果,有圓角邊框,logo和二維碼間有空白區,logo帶有灰色邊框
  * @author: huxm
 * @date: 2018年8月29日 下午12:10:35 
 * @version: v1.0.0
 *
 */
public class LogoConfig {
	
	/**
	 * 設定 logo 
	 * @param matrixImage 源二維碼圖片
	 * @return 返回帶有logo的二維碼圖片
	 * @throws IOException
	 * @author Administrator sangwenhao
	 */
     public BufferedImage LogoMatrix(BufferedImage matrixImage) throws IOException{
    	 /**
          * 讀取二維碼圖片,並構建繪圖物件
          */
         Graphics2D g2 = matrixImage.createGraphics();
    	 
    	 int matrixWidth = matrixImage.getWidth();
    	 int matrixHeigh = matrixImage.getHeight();
    	 
         /**
          * 讀取Logo圖片
          */
         BufferedImage logo = ImageIO.read(new File(""));
 
         //開始繪製圖片
         g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//繪製     
         BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); 
         g2.setStroke(stroke);// 設定筆畫物件
         //指定弧度的圓角矩形
         RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
         g2.setColor(Color.white);
         g2.draw(round);// 繪製圓弧矩形
         
         //設定logo 有一道灰色邊框
         BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND); 
         g2.setStroke(stroke2);// 設定筆畫物件
         RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
         g2.setColor(new Color(128,128,128));
         g2.draw(round2);// 繪製圓弧矩形
         
         g2.dispose();
         matrixImage.flush() ;
         return matrixImage ;
     }
    
}
/**
 * @Package: com.thinkgem.jeesite.common.qrcode
 * @author: huxm   
 * @date: 2018年8月29日 下午12:10:35 
 */
package com.thinkgem.jeesite.common.qrcode;
   
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
     
    /**
     * 二維碼的生成需要藉助MatrixToImageWriter類,該類是由Google提供的,可以將該類直接拷貝到原始碼中使用,當然你也可以自己寫個
     * 生產條形碼的基類
     */
    public class MatrixToImageWriter {
    	private static final int BLACK = 0xFF000000;//用於設定圖案的顏色
    	private static final int WHITE = 0xFFFFFFFF; //用於背景色
     
    	private MatrixToImageWriter() {
    	}
     
    	public static BufferedImage toBufferedImage(BitMatrix matrix) {
    		int width = matrix.getWidth();
    		int height = matrix.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,  (matrix.get(x, y) ? BLACK : WHITE));
    //				image.setRGB(x, y,  (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
    			}
    		}
    		return image;
    	}
     
    	public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
    		BufferedImage image = toBufferedImage(matrix);
    		//設定logo圖示
    		/*LogoConfig logoConfig = new LogoConfig();
    		image = logoConfig.LogoMatrix(image);*/
    		
    		if (!ImageIO.write(image, format, file)) {
    			throw new IOException("Could not write an image of format " + format + " to " + file);
    		}else{
    			System.out.println("圖片生成成功!");
    		}
    	}
     
    	public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
    		BufferedImage image = toBufferedImage(matrix);
    		//設定logo圖示
    		/*LogoConfig logoConfig = new LogoConfig();
    		image = logoConfig.LogoMatrix(image);*/
    		
    		if (!ImageIO.write(image, format, stream)) {
    			throw new IOException("Could not write an image of format " + format);
    		}
    	}
    	
    	public static void Encode_QR_CODE(String contents,String format,String path,int width,int height,int encodeHintType) throws IOException, WriterException{
    		
    		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
    		 // 指定糾錯等級,糾錯級別(L 7%、M 15%、Q 25%、H 30%)
    		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    		// 內容所使用字符集編碼
    		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");	
//    		hints.put(EncodeHintType.MAX_SIZE, 350);//設定圖片的最大值
//    	    hints.put(EncodeHintType.MIN_SIZE, 100);//設定圖片的最小值
    		hints.put(EncodeHintType.MARGIN, encodeHintType);//設定二維碼邊的空度,非負數
    		
    		BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,//要編碼的內容
    				//編碼型別,目前zxing支援:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
    				//Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
    				//MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
    				BarcodeFormat.QR_CODE,
    				width, //條形碼的寬度
    				height, //條形碼的高度
    				hints);//生成條形碼時的一些配置,此項可選
    		
    		// 生成二維碼
    		File outputFile = new File(path);//指定輸出路徑
    		
    		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
    	}
    }
/**
 * @Package: com.thinkgem.jeesite.common.qrcode
 * @author: huxm   
 * @date: 2018年8月29日 下午12:10:35 
 */
package com.thinkgem.jeesite.common.qrcode;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.thoughtworks.xstream.io.path.Path;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
/**
 * @Description: 生成二維碼的工具類
 *
 * @author: huxm
 * @date: 2018年8月29日 下午12:10:35 
 * @version: v1.0.0
 */
public class QRCodeUtil {
	 private static final String CHARSET = "utf-8";
	    private static final String FORMAT_NAME = "JPG";
	    // 二維碼尺寸
	    private static final int QRCODE_SIZE = 100;
	    // LOGO寬度
	    private static final int WIDTH = 30;
	    // LOGO高度
	    private static final int HEIGHT = 30;


	    /**
	     * 生成二維碼
	     * @param content   源內容
	     * @param imgPath   生成二維碼儲存的路徑
	     * @param needCompress  是否要壓縮
	     * @return      返回二維碼圖片
	     * @throws Exception
	     */
	    private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
	        Hashtable 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 (imgPath == null || "".equals(imgPath)) {
	            return image;
	        }
	        // 插入圖片
	        QRCodeUtil.insertImage(image, imgPath, needCompress);
	        return image;
	    }

	    /**
	     * 在生成的二維碼中插入圖片
	     * @param source
	     * @param imgPath
	     * @param needCompress
	     * @throws Exception
	     */
	    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
	        File file = new File(imgPath);
	        //System.out.println(file+"****************************");
	        if (!file.exists()) {
	            System.err.println("" + imgPath + "   該檔案不存在!");
	            return;
	        }
	        Image src = ImageIO.read(new File(imgPath));
	        int width = src.getWidth(null);
	        int height = src.getHeight(null);
	        if (needCompress) { // 壓縮LOGO
	            if (width > WIDTH) {
	                width = WIDTH;
	            }
	            if (height > HEIGHT) {
	                height = 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;
	        }
	        // 插入LOGO
	        Graphics2D 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();
	    }

	    /**
	     * 生成帶logo二維碼,並儲存到磁碟
	     * @param content   連結或者內容
	     * @param imgPath   logo圖片
	     * @param destPath  儲存二維碼圖片的檔案路徑
	     * @param needCompress
	     * @throws Exception
	     */
	    public static Boolean encode(String content, String imgPath, String destPath, boolean needCompress,String random) throws Exception {
	        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
	        if(image==null){
	            return false;
	        }
	        mkdirs(destPath);
	        String file = random + ".jpg";//生成隨機檔名
	        ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
	        return true;
	    }

	    public static void mkdirs(String destPath) {
	        File file = new File(destPath);
	        // 當資料夾不存在時,mkdirs會自動建立多層目錄,區別於mkdir。(mkdir如果父目錄不存在則會丟擲異常)
	        if (!file.exists() && !file.isDirectory()) {
	            file.mkdirs();
	        }
	    }

	    public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)
	            throws Exception {
	        BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
	        ImageIO.write(image, FORMAT_NAME, output);
	    }

	    public static void encode(String content, OutputStream output) throws Exception {
	        QRCodeUtil.encode(content, null, output, false);
	    }


	    /**
	     * 從二維碼中,解析資料
	     * @param file  二維碼圖片檔案
	     * @return   返回從二維碼中解析到的資料值
	     * @throws Exception
	     */
	    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 hints = new Hashtable();
	        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
	        result = new MultiFormatReader().decode(bitmap, hints);
	        String resultStr = result.getText();
	        return resultStr;
	    }

	    public static String decode(String path) throws Exception {
	        return QRCodeUtil.decode(new File(path));
	    }
	    
	    @SuppressWarnings({"rawtypes", "unchecked"})
	    private static void createZxing() throws WriterException, IOException {
	        int width=300;
	        int hight=300;
	        String format="png";
	        String content="www.baidu.com";
	        HashMap hints=new HashMap();
	        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
	        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//糾錯等級L,M,Q,H
	        hints.put(EncodeHintType.MARGIN, 2); //邊距
	        BitMatrix bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, hight, hints);
	        Path file=(Path) new File("D:/download/imag.png").toPath();
	        MatrixToImageWriter.writeToPath(bitMatrix, format, (java.nio.file.Path) file);
	    }
	    
	    private static void readZxing() throws IOException, NotFoundException {
	        MultiFormatReader read = new MultiFormatReader();
	        File file=new File("D:/download/imag.png");
	        BufferedImage image=ImageIO.read(file);
	        Binarizer binarizer=new HybridBinarizer(new BufferedImageLuminanceSource(image));
	        BinaryBitmap binaryBitmap=new BinaryBitmap(binarizer);
	        Result res=read.decode(binaryBitmap);
	        System.out.println(res.toString());
	        System.out.println(res.getBarcodeFormat());
	        System.out.println(res.getText());
	    }
}
//根據內容生成二維碼
String imgPath = "/static/images/qrcode/";//生成的路徑
String path = request.getSession().getServletContext().getRealPath(imgPath);//路徑整合
String code = "xxxxx";//生成的內容(可以是文字數字或者網址)
String imgName= code+".jpg";//生成二維碼圖片的名稱
String pathName = path+imgName;//生成的路徑名(儲存到資料庫的)
FileUtils.deleteFile(pathName);//呼叫檔案操作工具類刪除這個圖片(如果存在)
//呼叫工具類生成圖片(code:生成的內容;"jpg":生成的二維碼圖片格式;pathName:圖片生成的路徑;80:寬,高;1:二維碼周圍白邊的大小,如果不需要設為0,最大為5)
MatrixToImageWriter.Encode_QR_CODE(code, "jpg", pathName,80,80,1);


//如果需要生成帶logo的把工具類中註釋的LogoConfig去除,然後圖片給到