使用谷歌的zxing 来创建二维码
引入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
创建二维码
public class QRCodeUtil {
private static int width = 500;// 设定二维码的宽度
private static int height = 500;// 设定二维码的高度
private static String format = "png";// 设定二维码的图片格式
/**
*
* 由指定链接生成二维码
* 根据传入的链接,在指定文件夹内生成指定名称的二维码文件(png格式)
* @param url java.lang.String 要编入二维码的URL
* @param dir java.lang.String 存储文件夹名(必须存在)
*/
public static void createQRCode(String url,String dir) throws IOException {
//对二维码进行必要的设定
Map<EncodeHintType, Object> hints = new HashMap<>();
//二维码保存的图片名字使用UUID生成
String name= UUID.randomUUID().toString().replace("-","");
//设定内容的编码格式
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//设定图像的错误校正程度:
//M - ~15%
//L - ~7%
//H - ~30%
//Q - ~25%
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
//设定图像外边距(像素)
hints.put(EncodeHintType.MARGIN, 2);
try {
//进行编码并获得一个bit封装对象
BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
Path file = new File(dir, name +"." +format).toPath();
//使用默认设置、将bit封装对象以指定的图像格式、写入至指定文件中
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
//至此,一个二维码图像就生成完毕了,或者也可以使用下面的方法将其写出至输出流中
//MatrixToImageWriter.writeToStream(matrix, fileName, stream);
} catch (Exception e) {
e.printStackTrace();
}
}
}