1. 程式人生 > >二維碼生成工具類(需第三方的zxing包)

二維碼生成工具類(需第三方的zxing包)

package com.chinaepay.wx.common;


import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;


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


/**
 * 二維碼工具包。
 * 
 * @author xinwuhen
 */
public class QRCodeUtil {
private static QRCodeUtil qrCodeUtil = null;


private QRCodeUtil() {
}


public static QRCodeUtil getInstance() {
if (qrCodeUtil == null) {
qrCodeUtil = new QRCodeUtil();
}


return qrCodeUtil;
}


/**
* 根據引數生成二維碼圖片。

* @param imgCharactCode
*            字元編碼, 預設為:UTF-8.
* @param imgWidth
*            圖片寬度, 預設為: 300px
* @param imgHeight
*            圖片高度, 預設為: 300px
* @param strImgFileFoler
*     圖片儲存目錄
* @param imgFileName
*            圖片名稱(如:myTestQrImg.png)
* @param qrContent
*            二維碼內容
* @return 二維碼圖片的檔案物件
*/
public File genQrCodeImg(String imgCharactCode, int imgWidth, int imgHeight, String strImgFileFoler, String imgFileName, String qrContent) {
File imgFullFile = null;

if (strImgFileFoler == null || "".equals(strImgFileFoler) || imgFileName == null || "".equals(imgFileName) 
|| qrContent == null || "".equals(qrContent)) {
return imgFullFile;
}

BitMatrix bitMatrix = null;
try {
// 定義二維碼引數的雜湊對映表
HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
// 編碼方式,支援中文
imgCharactCode = (imgCharactCode == null || "".equals(imgCharactCode) ? "UTF-8" : imgCharactCode);
hints.put(EncodeHintType.CHARACTER_SET, imgCharactCode);
// 容錯等級
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 二維碼邊距
hints.put(EncodeHintType.MARGIN, 1);

// 生成點陣
imgWidth = (imgWidth <= 0 ? 300 : imgWidth);// 預設為300px
imgHeight = (imgHeight <= 0 ? 300 : imgHeight);// 預設為300px

bitMatrix = new MultiFormatWriter().encode(qrContent, BarcodeFormat.QR_CODE, imgWidth, imgHeight, hints);

// 建立目錄
File fileImgFoler = new File(strImgFileFoler);
if (!fileImgFoler.exists()) {
fileImgFoler.mkdir();
}

// 圖片的檔案物件
String strImgFullName = fileImgFoler.getPath() + "/" + imgFileName;
imgFullFile = new File(strImgFullName);

// 圖片副檔名(即:圖片格式)
Path filePath = imgFullFile.toPath();
String imgFormat = imgFileName.substring(imgFileName.lastIndexOf(".") + 1);

// 輸出檔案
MatrixToImageWriter.writeToPath(bitMatrix, imgFormat, filePath);
} catch (WriterException | IOException e) {
e.printStackTrace();
imgFullFile = null;
}

return imgFullFile;
}
}