java实现生成二维码的功能,需要用到谷歌的zxing包。所以实现功能的第一步就是在pom.xml配置文件中注入依赖,如下图。
依赖的代码形式就是:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
当然也可以从maven仓库下载jar包: http://central.maven.org/maven2/com/google/zxing/core/
注入依赖之后,开始实现二维码生成的功能:生成二维码,储存关键字“扫描二维码”并且把二维码以字节流的形式返回。
Controllar层设置http信息并且返回字节流:
/**
* 用户请求二维码
*
* @return
*/
@PostMapping(value = "/qrcode/plat")
@ResponseBody
public ResponseEntity<byte[]> getQRcode(@RequestBody LoginInformation loginInfo) throws IOException, WriterException {
HttpStatus httpStatus = HttpStatus.OK;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
ByteArrayOutputStream out = new ByteArrayOutputStream();
BitMatrix qrcode = loginServiceImpl.getQrcode(loginInfo);
if (qrcode != null) {
BufferedImage image = toBufferedImage(qrcode);
ImageIO.write(image, "png", out);
}
return new ResponseEntity<byte[]>(out.toByteArray(), headers, httpStatus);
}
service层设置二维码的具体信息并且生成二维码:
public BitMatrix getQrcode(LoginInformation loginInfo) throws WriterException, IOException {
int width = 300;
int height = 300;
String format = "png";
String contents = "扫描二维码";
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 = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
return bitMatrix;
}
代码完成之后,使用postman调用接口,可得生成的二维码。
扫描二维码可得:
如果想要是实现扫描二维码之后跳转到一个网页,那么就可以把contents关键字存储的信息换成网页地址。