java实现生成二维码

  二维码在我们日常生活中非常常见,在工作中也经常会用到生成二维码的相关知识,这里记录一下使用谷歌提供的依赖ZXing实现二维码的生成。

  1. 创建好项目之后,到maven中央仓库下载以下依赖:
  <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>core</artifactId>
      <version>3.3.3</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
    <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>javase</artifactId>
      <version>3.4.0</version>
    </dependency>

2.创建生成二维码的工具类

public class GetQRCord {

	/**
	 * 定义二维码相关配置
	 */
	public static void definitQRCord() {
		//定义二维码宽度
		int width = 600;
		//定义二维码高度
		int heigh = 600;
		//定义图片格式
		String type = "png";
		//定义扫码内容
		String content = "www.baidu.com";
		//定义二维码配置
		HashMap configMap = new HashMap();
		//定义字符集
		configMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
		//设置容错等级
		configMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		//设置边距
		configMap.put(EncodeHintType.MARGIN, 2);
		try {
			//生成二维码
			BitMatrix bitMatrix = new MultiFormatWriter()
					.encode(content, BarcodeFormat.QR_CODE, width,heigh,configMap);
			//定义路径
			Path path = new File("D:" + File.separator + "photo"+File.separator+"QRCode.png").toPath();
			//生成路径并生成文件
			MatrixToImageWriter.writeToPath(bitMatrix,type,path);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
  1. 测试工具类是否能够正常生成:
@SpringBootTest
class DemoApplicationTests {

	@Test
	void contextLoads() {
		definitQRCord();
	}
}

测试结果:本地磁盘中成功生成二维码图片
在这里插入图片描述

发布了79 篇原创文章 · 获赞 42 · 访问量 7971

猜你喜欢

转载自blog.csdn.net/qq_43655835/article/details/103687773