關於使用谷歌矩陣代碼生成微信二維碼的方法

注意:請先檢查是否在maven中添加了fastjson以及谷歌zxing的依賴包,本示例使用的依賴包及對應版本如下:

<dependencies>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.0.0</version>
		</dependency>
		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.0.0</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.1.29</version>
		</dependency>
</dependencies>

測試代碼如下:

public class QRCodeTest {

	@Test
	public void test() throws WriterException, IOException {
		//生成二維碼的路徑
		String filePath = "D://";
		//圖片名稱
		String fileName = "qrCodeTest.png";
		
		//使用fastjson創建jsonObject對象
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("company", "www.kinglong.com");
		jsonObject.put("author", "kinglong");
		
		//將json對象轉換爲json格式的字符串
		String content = jsonObject.toJSONString();
		
		//設置畫布大小
		int width = 200;//寬度
		int height = 200;//高度
		
		//設置字符編碼集,採用utf-8的字符編碼
		Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		
		//生成矩陣
		BitMatrix bitMatrix = new MultiFormatWriter().encode("weixin://wxpay/bizpayurl?pr=KKmqnXS", BarcodeFormat.QR_CODE, width, height, hints);
		
		//生成路徑
		Path path = FileSystems.getDefault().getPath(filePath, fileName);
		
		//輸出文件至指定的路徑
		MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
		
		
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章