代碼
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
/**
* @author Yawei Xi
* @date 2018-7-9
*/
public class QrCodeUtil {
/**
* 創建二維碼圖片
*
* @param content 二維碼攜帶信息
* @param qrCodeSize 二維碼圖片大小
* @param filePath 生成的二維碼圖片的保存的路徑
*/
public static void createQrCodeImage(String content, int qrCodeSize, String filePath) {
try {
BufferedImage bi = createQrCode(content, qrCodeSize);
File imgFile = new File(filePath);
ImageIO.write(bi, "JPEG", imgFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成包含字符串信息的二維碼圖片
*
* @param content 二維碼攜帶信息
* @param qrCodeSize 二維碼圖片大小
*/
private static BufferedImage createQrCode(String content, int qrCodeSize) {
try {
// 設置二維碼糾錯級別Map
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
// 矯錯級別
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
// 創建比特矩陣(位矩陣)的QR碼編碼的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
// 使BufferedImage勾畫QRCode (matrixWidth 是行二維碼像素點)
int matrixWidth = byteMatrix.getWidth();
int matrixHeight = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth - 65, matrixWidth - 65, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixHeight);
// 使用比特矩陣畫並保存圖像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i - 33, j - 33, 2, 2);
}
}
}
return image;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
測試用例
/**
* @author Yawei Xi
* @since 2018-7-9 10:17
*/
public class Test {
public static void main(String[] args) throws Exception {
// 需要二維碼攜帶的內容
String content = "All I need is someone who makes me wanna sing.";
// 生成二維碼的大小
int qrCodeSize = 900;
// 將二維碼保存的路徑
String filePath = "D:\\testQRImage.jpg";
// 執行工具類,生成二維碼
QrCodeUtil.createQrCodeImage(content, qrCodeSize, filePath);
}
}
測試結果
- 在指定路徑產生一個二維碼圖片,打開圖片,用手機掃碼后的結果如下:
All I need is someone who makes me wanna sing.