代码实现
本例使用maven项目创建
- 注入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
- 创建工具类
private static boolean orCode(String content, String path) {
/*
* 图片的宽度和高度
*/
int width = 300;
int height = 300;
// 图片的格式
String format = "png";
// 定义二维码的参数
HashMap hints = new HashMap();
// 定义字符集编码格式
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
// 纠错的等级 L > M > Q > H 纠错的能力越高可存储的越少,一般使用M
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 设置图片边距
hints.put(EncodeHintType.MARGIN, 2);
try {
// 最终生成 参数列表 (1.内容 2.格式 3.宽度 4.高度 5.二维码参数)
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
// 写入到本地
Path file = new File(path).toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
return true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
本例中传入二维码保存的内容和保存二维码的路径即可
- 测试代码
public static void main(String[] args) {
// 传参:二维码内容和生成路径
if (orCode("http://baidu.com", "F:\\1.jpg")) {
System.out.println("ok,成功");
} else {
System.out.println("no,失败");
}
}
拆分说明
- 宽高的设值
int width = 300;
int height = 300;
对已生成的二维码放大缩小容易失真,也可将其添加到方法参数中,建议确定其大小
- 参数content
content参数可以是“正常内容”也可以是网址
如:
“baidu.com”为内容
“http://baidu.com”直接跳转到网址 - 二维码参数列表
// 最终生成 参数列表 (1.内容 2.格式 3.宽度 4.高度 5.二维码参数)
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
查询源码可知MultiFormatWriter继承Writer并实现了encode方法
并根据不同的参数格式,如BarcodeFormat.QR_CODE返回不同的Writer
此例中返回的为QRCodeWriter实例,并在该实例中解析hints,如下:
if (hints != null) {
if (hints.containsKey(EncodeHintType.ERROR_CORRECTION)) {
errorCorrectionLevel = ErrorCorrectionLevel.valueOf(hints.get(EncodeHintType.ERROR_CORRECTION).toString());
}
if (hints.containsKey(EncodeHintType.MARGIN)) {
quietZone = Integer.parseInt(hints.get(EncodeHintType.MARGIN).toString());
}
}
- 写入本地
Path file = new File(path).toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
本例在MatrixToImageWriter的writeToPath传入Path参数
也可以传入File参数,源码实现如下:
public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
writeToPath(matrix, format, file.toPath());
}
public static void writeToPath(BitMatrix matrix, String format, Path file) throws IOException {
writeToPath(matrix, format, file, DEFAULT_CONFIG);
}
以上。