1. 程式人生 > >生成二維碼

生成二維碼

方法 pan content ima common logging 後臺 con depend

這是google的一個二維碼工具

導入jar

方式一【gradle :"com.google.zxing:core:3.3.0" 】

方式二【maven:

<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>

方式三 下載鏈接: https://pan.baidu.com/s/1geG0HZP 密碼: z7rq

使用的時候,定義一個方法即可:
 1 package com.mall.core.utils;
 2 
 3 import com.google.zxing.BarcodeFormat;
 4 import com.google.zxing.EncodeHintType;
 5 import com.google.zxing.MultiFormatWriter;
 6 import com.google.zxing.WriterException;
 7 import com.google.zxing.common.BitMatrix;
 8 import org.apache.logging.log4j.LogManager;
9 import org.apache.logging.log4j.Logger; 10 11 import java.awt.image.BufferedImage; 12 import java.util.HashMap; 13 import java.util.Map; 14 15 /** 16 * Created by lier on 2017/5/12. 17 */ 18 public class QrCodeUtils { 19 20 private static final Logger logger = LogManager.getLogger(QrCodeUtils.class
); 21 //二維碼顏色 22 private static final int BLACK = 0xFF000000; 23 //二維碼顏色 24 private static final int WHITE = 0xFFFFFFFF; 25 26 /** 27 * ZXing 方式生成二維碼 28 * @param text 二維碼內容 29 * @param width 二維碼寬 30 * @param height 二維碼高 31 * @return BufferedImage 32 */ 33 public static BufferedImage createQrcode(String text, int width, int height){ 34 BufferedImage image = null; 35 Map<EncodeHintType, String> his = new HashMap<>(); 36 //設置編碼字符集 37 his.put(EncodeHintType.CHARACTER_SET, "utf-8"); 38 try { 39 //1、生成二維碼 40 BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his); 41 42 //2、獲取二維碼寬高 43 int codeWidth = encode.getWidth(); 44 int codeHeight = encode.getHeight(); 45 46 //3、將二維碼放入緩沖流 47 image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB); 48 for (int i = 0; i < codeWidth; i++) { 49 for (int j = 0; j < codeHeight; j++) { 50 //4、循環將二維碼內容定入圖片 51 image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE); 52 } 53 } 54 } catch (WriterException e) { 55 logger.info("生成二維碼失敗", e); 56 } 57 return image; 58 } 59 }

在頁面中顯示二維碼:

<img src="${pageContext.request.contextPath}/qrcode?name=我的名字">

後臺代碼:

1 @RequestMapping(value = "/qrcode")
2     public void qrCode(HttpServletResponse response, String name) throws IOException {
3         //把接收到的參數name 生成到二維碼裏面
4         BufferedImage qrcode = QrCodeUtils.createQrcode(name, 200, 200);
5         response.setContentType("image/jpeg");
6         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(response.getOutputStream());
7         encoder.encode(qrcode);
8     }

生成二維碼