在SpringMVC使用Zxing生成二维码图片
在SpringMVC使用Zxing生成二维码图片:
1. 在Pom.xml引用Zxing
<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>
2. 在Controller中使用HttpServletResponse输出图片流
@RequestMapping(value = "/ReceivingMoneyQRCode", method = RequestMethod.GET)
public void ReceivingMoneyQRCode(HttpServletResponse response, String accountCode) throws IOException {
String url = "要生成二维码的地址" + accountCode;
ServletOutputStream stream = null;
try {
int width = 200;
int height = 200;
stream = response.getOutputStream();
QRCodeWriter writer = new QRCodeWriter();
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width,hints);
MatrixToImageWriter.writeToStream(m, "png", stream);
} catch (WriterException e) {
e.printStackTrace();
} finally {
if (stream != null) {
stream.flush();
stream.close();
}
}
}
参考
- 谷歌Zxing二维码,用数据流输出到页面显示
解决中文乱码的问题,因为ZXing默认使用iso-8859-1编码,使用utf-8解决乱码问题:
Hashtable hints = new Hashtable(); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); encode(String contents, BarcodeFormat format, int width, int height,Hashtable hints)
参考:How do I encode characters using UTF-8 in a QR code using Zxing project?
在输出图片流时,提示
Can't create output stream!
。通过查看日志,发现是因为:Can't create cache file!
,再往下是因为AccessDenied,不能在Tomcat中生成临时图片文件。通过在启动IntelliJ时,使用管理员身份运行解决。