maven导入第三方库
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
开放API接口
@RequestMapping(value = "qrcode/{w}/{h}", method = RequestMethod.GET)
public void qrcode(@RequestParam("url") String url, @PathVariable(value = "w") Integer width, @PathVariable(value = "h") Integer height, HttpServletRequest request, HttpServletResponse response) {
try {
url = new String(new BASE64Decoder().decodeBuffer(url));
} catch (IOException e) {
LOGGER.error("BASE64进行URL解码失败");
}
String format = "png";
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix = null;
File outputFile = new File("tmp.png");
try {
bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
} catch (WriterException | IOException e) {
LOGGER.error("写入失败:"+e.getMessage());
}
FileInputStream fis = null;
response.setContentType("image/png");
try {
OutputStream out = response.getOutputStream();
fis = new FileInputStream(outputFile);
byte[] b = new byte[fis.available()];
fis.read(b);
out.write(b);
out.flush();
} catch (Exception e) {
LOGGER.error("请求失败:" + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
还没有评论,来说两句吧...