一、介绍:本文为二维码不在服务器生成图片直接输出在客户端;访问方式可以为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;
}