注意:请先检查是否在maven中添加了fastjson以及谷歌zxing的依赖包,本示例使用的依赖包及对应版本如下:
<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.29</version>
</dependency>
</dependencies>
测试代码如下:
public class QRCodeTest {
@Test
public void test() throws WriterException, IOException {
//生成二维码的路径
String filePath = "D://";
//图片名称
String fileName = "qrCodeTest.png";
//使用fastjson创建jsonObject对象
JSONObject jsonObject = new JSONObject();
jsonObject.put("company", "www.kinglong.com");
jsonObject.put("author", "kinglong");
//将json对象转换为json格式的字符串
String content = jsonObject.toJSONString();
//设置画布大小
int width = 200;//宽度
int height = 200;//高度
//设置字符编码集,采用utf-8的字符编码
Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//生成矩阵
BitMatrix bitMatrix = new MultiFormatWriter().encode("weixin://wxpay/bizpayurl?pr=KKmqnXS", BarcodeFormat.QR_CODE, width, height, hints);
//生成路径
Path path = FileSystems.getDefault().getPath(filePath, fileName);
//输出文件至指定的路径
MatrixToImageWriter.writeToPath(bitMatrix, "png", path);
}
}