导入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.0</version>
</dependency>
方法
public static void QREncode(String text, String imgName) throws WriterException, IOException {
String content = text;//二维码内容
int width = 200; // 图像宽度
int height = 200; // 图像高度
String format = "jpg";// 图像类型
String path = "D:\\QRCode\\" + imgName + "." + format;
Map<EncodeHintType, Object> hints = new HashMap<>();
//内容编码格式
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//设置二维码边的空度,非负数
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToPath(bitMatrix, format, new File(path).toPath());// 输出原图片
MatrixToImageConfig matrixToImageConfig = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
System.out.println("输出成功.");
}
调用
try {
QREncode("二维码内容", "二维码图片名字");
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}