一、介紹:本文爲二維碼不在服務器生成圖片直接輸出在客戶端;訪問方式可以爲img標籤中src爲“aa/getQCode?text=”;
二、二維碼生成器分爲兩種,小日本的qCord導入谷歌zxing的jar包;其中zxing的maven依賴是:
<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>
三、代碼部分:
@RequestMapping(value = "getQRCoder")
@ResponseBody
public void getQRCoder(HttpServletResponse response,String text){
//設置頁面不緩存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width2 = 233;
int height2 = 233;
//二維碼的圖片格式
Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
//內容所使用編碼
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(text,BarcodeFormat.QR_CODE, width2, height2, hints);
bitMatrix = deleteWhite(bitMatrix);
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); //二維碼圖片爲黑白兩色
}
}
ImageIO.write(image,"gif",response.getOutputStream());
//生成二維碼
//File outputFile = new File("d:"+File.separator+"new.gif");
//MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static BitMatrix deleteWhite(BitMatrix matrix) {
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;
BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}