java善假於物(一):利用google提供jar生成二維碼

介紹

在實際開發中,二維碼生成是很常見的,然而google給咱們提供了一套快捷生成二維碼的jar,下面咱們來研究一下怎麼使用.java

1.maven配置

<!-- 谷歌二維碼 -->
<dependency>
	<groupId>com.google.zxing</groupId>
	<artifactId>core</artifactId>
	<version>3.2.1</version>
</dependency>

2.建立一個二維碼生成工具類QRCodeUtil .java

package com.cppba.core.util;

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;

import java.awt.image.BufferedImage;
import java.util.Hashtable;

public class QRCodeUtil {

	/**
	 *
	 * QRCodeCreate(生成二維碼)
	 * @param content  二維碼內容
	 * @param W		寬度
	 * @param H		高度
	 * @return
	 */
	public static BufferedImage QRCodeCreate(String content, Integer W, Integer H){
		//生成二維碼
		MultiFormatWriter mfw = new MultiFormatWriter();
		BitMatrix bitMatrix = null;
		Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		hints.put(EncodeHintType.MARGIN, 0);
		try {
			bitMatrix = mfw.encode(content, BarcodeFormat.QR_CODE, W, H,hints);
		} catch (WriterException e) {
			e.printStackTrace();
		}
		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);
			}
		}
		return image;
	}
}

3.寫一個測試的Controller

/**
 * 獲取二維碼
 * text 必須用UTF8編碼格式,x內容出現 & 符號時,請用 %26 代替,換行符使用 %0A
 */
@RequestMapping("/qrcode_image.htm")
public void qrcode_image(
		HttpServletRequest request,HttpServletResponse response,
		@RequestParam(value="text", defaultValue="")String text) throws IOException {

	response.setHeader("Pragma", "No-cache");
	response.setHeader("Cache-Control", "no-cache");
	response.setDateHeader("Expires", 0);
	response.setContentType("image/jpeg");

	BufferedImage image = QRCodeUtil.QRCodeCreate(text, 250, 250);

	ImageIO.write(image, "png",response.getOutputStream());
}

4.測試

咱們啓動咱們的項目,在瀏覽器直接訪問咱們測試控制器,並帶上參數 我這裏是:http://127.0.0.1:8080/cppba-web/qrcode_image.htm?text=http://www.baidu.comgit

5.運行結果

https://github.com/bigbeef/cppba-web 咱們能夠有手機掃描一下二維碼,的確進的是百度首頁,固然你能夠本身修改text參數來動態生成你想要的二維碼內容github

6.注意

這裏要提醒的是,text中不能帶有「&「和換行符,當遇到這種符號時:& 符號用 %26 代替,換行符使用 %0A代替。web

github地址:https://github.com/bigbeef 我的博客:http://www.cppba.com瀏覽器

相關文章
相關標籤/搜索