pom配置
<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>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.29</version>
</dependency>
生成一串包含json数据的二维码
- 此方法会生成一个二维码, 手机扫描后得到一串json数据
public class QRCodeTest {
public static void main(String[] args) throws WriterException, IOException {
String filePath = "D://";
String fileName = "zxing.png";
JSONObject json = new JSONObject();
json.put("zxing", "https://www.baidu.com");
json.put("author", "yangzhongyang");
String content = json.toJSONString(); //内容
int width = 200; //图像宽度
int height = 200; //图像高度
String format = "png"; //图像类型
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter()
.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
Path path = FileSystems.getDefault().getPath(filePath, fileName);
MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
}
}
生成一个带Url连接的二维码
- 此方法生成二维码包含一个Url地址连接, 使用手机扫描后会自动跳转到指定的Url地址
public static void main(String[] args) throws WriterException, IOException {
String filePath = "D://";
String fileName = "zxing.png";
int width = 200; //图像宽度
int height = 200; //图像高度
String format = "png"; //图像类型
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter()
.encode("http://www.huiedu.com.cn", BarcodeFormat.QR_CODE, width, height, hints);
Path path = FileSystems.getDefault().getPath(filePath, fileName);
MatrixToImageWriter.writeToPath(bitMatrix, format, path);// 输出图像
}
网友评论