Java二维码的生成。
文章目录
后端生成二维码
1.后台生成二维码接口,传入参数:高、宽、二维码内容,可生成相应高宽含该内容的二进制流(二维码图片),不传高宽则默认二维码的大小为200*200。
/*
* 生成二维码
* */
@RequestMapping(path = "/createQRCode",method = RequestMethod.POST)
@ResponseBody
public void createQRCode(@InterfaceParam(name="data") String data,
@InterfaceParam(name="height") Integer height ,
@InterfaceParam(name="width") Integer width,HttpServletResponse response) throws Exception, BaseException {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
int ht=200;
int wt=200;
BufferedImage image = QRCodeCloudPrintUtil.createImage(data,null==height?ht:height,null==width?wt:width);
// 创建二进制的输出流
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(image, "jpeg", sos);
}
2.createImage方法如下:
public static BufferedImage createImage(String content,int ht,int wt) {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, wt, ht, hints);
} catch (WriterException e) {
e.printStackTrace();
}
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);
}
}
return image;
}
3.使用postman调用如下: