1. 程式人生 > >多種方式實現二維碼

多種方式實現二維碼

最近和一位前輩學習生成二維碼(Zxing,Qrcode,Jquery)3種方式,整理了一份簡單資料分享給大家。本人編碼閱歷有限,下文程式碼中存在編碼規範問題,還請多多留言。

下文所提到的工具包:雙擊免費工具包下載

提取碼:gm03

Zxing

谷歌推出的一款開源專案。

需要包:

zxing-3.3.2.jar

建立二維碼

package student.com.zxing;

import java.io.File;

import java.nio.file.Path;
import java.util.HashMap;
import java.util.UUID;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * 
 * @author Bad Written
 *
 */
public class CreateZxing {
	
	/**
	 * 
	 * @param content
	 * @param width
	 * @param height
	 * @param charsetName
	 * @return BitMatrix物件(儲存將要生成的二維碼的位元組資料)
	 * @throws Exception 
	 */
	public static BitMatrix createBitMatrix(String content, int width, int height,String charsetName) throws Exception{
		//要生成什麼格式的二維碼
		BitMatrix bitMatrix=null;
		//二維碼當中要儲存什麼資訊
		HashMap<EncodeHintType, Comparable> hints = new HashMap<EncodeHintType, Comparable>();
		hints.put(EncodeHintType.CHARACTER_SET, charsetName);
		//設定糾錯率,分為L、M、H三個等級,等級越高,糾錯率越高,但儲存的資訊越少
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		//設定一下邊距,預設是5
		hints.put(EncodeHintType.MARGIN, 2);
		bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
		return bitMatrix;
	}
	
	/**
	 * 
	 * @param content 內容
	 * @param format 圖片格式
	 * @param width 圖片寬
	 * @param height 高
	 * @param charsetName 編碼格式
	 * @param filepath 檔案路徑
	 * @throws Exception
	 */
	public static void create(String content,String format, int width, int height,String charsetName,String filepath) throws Exception{
		BitMatrix bitMatrix=CreateZxing.createBitMatrix(content, width, height,charsetName);		
		File file=new File(filepath+File.separator+UUID.randomUUID().toString().replace("-", "")+"."+format);
		Path path = file.toPath();
		MatrixToImageWriter.writeToPath(bitMatrix, format, path);
		
	}
	
	public static void main(String[] args){
		System.out.println("開始");
		try{
			CreateZxing.create("Zxing生成二維碼!","png",300,300,"utf-8","E:/code");
			System.out.println("成功");
		}catch(Exception e){
			e.printStackTrace();
		}
		
    }
}

 生成結果如圖:

Zxing

讀取二維碼

package study.com.zxing;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

/**
 * 
 * @author Bad Written
 *
 */
public class ReadZxingCode {

	public static Result read(String filepath,String charsetName) throws IOException, NotFoundException{
		Result result=null;
		MultiFormatReader mfr=new MultiFormatReader();
		File file=new File(filepath);
		BufferedImage img=ImageIO.read(file);
		BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(img)));		
		HashMap hints = new HashMap();
		hints.put(EncodeHintType.CHARACTER_SET,charsetName);		
		result=mfr.decode(binaryBitmap,hints);
		return result;
	}
	
	public static void main(String[] args){
		System.out.println("開始");
		Result result;
		try {
			result = ReadZxingCode.read("E:/code/d4ebf9c4917f401da607df77ac50a346.png","utf-8");
			System.out.println(result.toString());
		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 QRcode

包:1.2\qrcode-1.2.jar

建立二維碼

package study.com.qrcode;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;
/*
 * 基於Graphics2D畫圖工具
 */
public class CreateQRCode {
	
	/**
	 * 返回一個圖片快取
	 * 
	 * @param context 圖片內容
	 * @param size 二維碼版本
	 * @charsetName 編碼格式
	 * @return
	 * @throws IOException
	 */
	private static BufferedImage createbuf(String context,int size,String charsetName) throws IOException{
		//二維碼類
		Qrcode qr=new Qrcode();
		//糾錯等級
		qr.setQrcodeErrorCorrect('M');
		//代表其他字元
		qr.setQrcodeEncodeMode('B');
		//設定設定二維碼尺寸,取值範圍1-40,值越大尺寸越大,可儲存的資訊越大
		qr.setQrcodeVersion(size);
		//二維碼大小
		int width=67+12*(size-1);//公式
		int height=67+12*(size-1);
		//緩衝區圖片
		BufferedImage bufimg=new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//畫圖工具
		Graphics2D gs=bufimg.createGraphics();
		
		gs.setBackground(Color.WHITE);
		gs.setColor(Color.BLACK);
		//設定畫板
		gs.clearRect(0, 0, width, height);
		//內容編碼
		byte[] d=context.getBytes(charsetName);
		
		int pixoff=2;//偏移量
		// 輸出內容> 二維碼 
		if(d.length>0 && d.length<120){			
			boolean[][] s=qr.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);
					}
				}
			}
		}
		gs.dispose();
		bufimg.flush();
		return bufimg;
	}
	
	/**
	 * 
	 * @param context 內容
	 * @param size   版本
	 * @param type  圖片格式
	 * @param imgpath 圖片路徑
	 * @throws IOException
	 */
	public static void create(String context,int size,String type,String imgpath) throws IOException{
		BufferedImage bufimg=CreateQRCode.createbuf(context,size,"gb2312");		
		File file=new File(imgpath+File.separator+UUID.randomUUID().toString().replace("-", "")+"."+type);
		ImageIO.write(bufimg, type, file);	
	}
		
	public static void main(String[] args) {
		System.out.println("開始"+File.separator);
		try{
			CreateQRCode.create("Qrcode生成二維碼", 7, "png", "E:/code");
			System.out.println("成功");
		}catch(IOException e){
			System.out.println("失敗");
			e.printStackTrace();
		}		
	}
}

生成二維碼如圖:

Qrcode

讀取二維碼

主工具類 

package study.com.qrcode;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;

public class ReadQrCode {

	/**
	 * 
	 * @param filepath 檔案路徑
	 * @param charsetName 編碼格式
	 * @return 解析出來結果
	 * @throws IOException
	 */
	public static String read(String filepath,String charsetName) throws IOException{
		String result=null;
		File file=new File(filepath);
		BufferedImage img=ImageIO.read(file);
		QRCodeDecoder qrCodeDecoder=new QRCodeDecoder();
		result=new String(qrCodeDecoder.decode(new QrCodeImgImp(img)),charsetName);				
		return result;
	}
	
	public static void main(String[] args) throws IOException{
		String str=ReadQrCode.read("E:/code/qrcode.png","gb2312");
		System.out.println("解析:"+str);
	}
	
}

副類

package study.com.qrcode;

import java.awt.image.BufferedImage;

import jp.sourceforge.qrcode.data.QRCodeImage;

public class QrCodeImgImp implements QRCodeImage {

	BufferedImage bufimg;
	
	public QrCodeImgImp(BufferedImage bufimg){
		this.bufimg=bufimg;		
	}
	
	public int getHeight() {
		// TODO Auto-generated method stub
		return bufimg.getHeight();
	}

	public int getPixel(int arg0, int arg1) {
		// TODO Auto-generated method stub
		return bufimg.getRGB(arg0, arg1);
	}

	public int getWidth() {
		// TODO Auto-generated method stub
		return bufimg.getWidth();
	}

}

JQuery

匯入相應的JS

jquery.qrcode.min.js
           jquery-3.3.1.min.js

生成二維碼

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>生成二維碼</title>
	</head>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.qrcode.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$('#qrcode').qrcode(
		{
		    render : "canvas",    //設定渲染方式,有table和canvas,使用canvas方式渲染效能相對來說比較好  
		    text : "http://www.baidu.com",    //掃描二維碼後顯示的內容,可以直接填一個網址,掃描二維碼後自動跳向該連結  
		    width : "200",               //二維碼的寬度  
		    height : "200",         //二維碼的高度  
		    background : "#ffffff",       //二維碼的後景色  
		    foreground : "#000000",        //二維碼的前景色  
		});
	}
)
</script>
	<body>
		生成二維碼如下
		<center> 
			<div id="qrcode"></div>
		</center> 
			<h3>顯示結束</h3>
	</body>
</html>