用Zxing 的core和javase包生成有中文的二维码,手机端无法识别的问题,在看了这个https://q.cnblogs.com/q/49762/博客后,想死的心都有了 ,
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 注意这里utf-8一定要小写
这样就可以解决手机不能识别的问题,而且也能支持中文。
至于原因,查看了源代码后,发现使用“UTF-8”,会在文本编码前添加一段ECI(扩充解释Extended Channel Interpretation)
编码,就是这段编码导致手机不能解析。如果使用小写"utf-8"会使这个ECI判断失效而不影响内容编码方式。
完整代码如下:
MultiFormatWriter writer = new MultiFormatWriter();
// 生成二维码
try {
String code = "name=正常注册的企业-审核通过"; // 二维码中的内容
HttpServletResponse response = ServletActionContext.getResponse ();
ServletOutputStream outStream = response.getOutputStream ();
Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
hints.put (EncodeHintType.CHARACTER_SET, "utf-8");// 注意这里utf-8一定要小写
//code = new String(code.getBytes("UTF-8"),"ISO-8859-1");//如果不想更改源码,则将字符串转换成ISO-8859-1编码
BitMatrix matrix = writer.encode (code, BarcodeFormat.QR_CODE, width, height, hints);
//BitMatrix matrix = writer.encode (code, BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToStream (matrix, "png", outStream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
<!-- zxing 二维码 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>2.2</version> </dependency>