SpringBoot生成二维码并扫码

07-16 1016阅读

文章目录

  • 一、引入依赖
  • 二、配置
    • 1.yml配置
    • 2.配置文件实体
    • 二维码生成工具类
    • 三、接口测试
    • 测试
      • 1、生成二维码
      • 手机扫码测试
      • 结束 ★★★★★

        一、引入依赖

        ZXing 是一个开源的条形码和二维码图像处理库,它提供了生成、解码和识别各种格式的条形码和二维码的功能。

        
            com.google.zxing
            javase
            3.2.1
        
        

        二、配置

        1.yml配置

        注意路径配置

        # 应用服务 WEB 访问端口
        server:
          port: 8080
        # 二维码配置
        qrCode:
          # 二维码url地址
          codeUrl: http://192.168.0.221:8080/code/codeUrl/
          # win路径
          codePath: C:/qr
          # linux路径
        #  codePath: /qr
        

        2.配置文件实体

        `

        代码如下(示例):

        /**
         * @description: 二维码配置实体
         * @program: ws-netty
         * @create: 2024-04-12 15:10
         * @author: whe
         **/
        @Data
        @Component
        public class QrCodeConfig {
            @Value("${qrCode.codeUrl}")
            private String codeUrl;
            @Value("${qrCode.codePath}")
            private String codePath;
            
        }
        

        二维码生成工具类

        /**
         * @description 将指定url转为二维码图片
         * @since 2020-11-05 16:58
         */
        @Slf4j
        public class QRCodeHelper {
        	private static final int BLACK = 0xFF000000;
        	private static final int WHITE = 0xFFFFFFFF;
        	/**
        	 * 二维码生成
        	 * @param url: url地址
        	 * @param path:二维码存储路径
        	 * @param fileName:二维码文件名
        	 * @return: 二维码地址
        	 */
        	public static String createQrCode(String url, String path, String fileName) {
        		try {
        			Map hints = new HashMap();
        			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        			 BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
        			File file = new File(path, fileName);
        			if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {
        				writeToFile(bitMatrix, "jpg", file);
        				log.info("生成二维码图片:" + file);
        				return file.toString();
        			}
        		} catch (Exception e) {
        			e.printStackTrace();
        		}
        		return null;
        	}
        	static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        		BufferedImage image = toBufferedImage(matrix);
        		if (!ImageIO.write(image, format, file)) {
        			throw new IOException("Could not write an image of format " + format + " to " + file);
        		}
        	}
        	private static BufferedImage toBufferedImage(BitMatrix matrix) {
        		int width = matrix.getWidth();
        		int height = matrix.getHeight();
        		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        		for (int x = 0; x  
        

        三、接口测试

        如果需要删除二维码,放开注释部分即可

        /**
         * @description: 测试控制层
         * @program: ws-netty
         * @create: 2024-04-12 14:46
         * @author: whe
         **/
        @RequestMapping("/code")
        @RestController
        public class QrCodeController {
            @Autowired
            private QrCodeConfig qrCodeConfig;
            /** 存储生成的二维码,用于删除 */
        //    private static List qRCodeImgList = new ArrayList();
            /**
             * 生成二维码
             * @param name: 二维码url参数(实际根据业务处理)
             * @return
             */
            @GetMapping("/create")
            public String createCode(String name){
                String url = qrCodeConfig.getCodeUrl() + "?name=" + name;
                String qrCodeImgPath = QRCodeHelper.createQrCode(url, qrCodeConfig.getCodePath(), name + ".jpg");
        //        File file = new File(qrCodeImgPath);
        //        qRCodeImgList.add(file);
                return qrCodeImgPath;
            }
            /**
             * 二维码url地址
             * @param name: 生成时携带的参数
             * @return
             */
            @GetMapping("/codeUrl")
            public String codeUrl(String name) {
                String msg = "获取二维码值为: " + name;
                System.out.println(msg);
        //        if (qRCodeImgList != null){
        //            qRCodeImgList.forEach(vo -> {
        //                vo.delete();
        //                System.out.println("删除二维码图片: " + vo.getAbsolutePath());
        //            });
        //            qRCodeImgList.clear();
        //        }
                return msg;
            }
        }
        

        测试

        1、生成二维码

        访问生成二维码接口地址:http://ip:8080/code/create?name=kun

        SpringBoot生成二维码并扫码

        本地正常生成文件

        SpringBoot生成二维码并扫码

        手机扫码测试

        手机扫码需要跟电脑要在同一局域网,电脑直接扫码没有问题

        此处的返回结果只是案例,可以根据实际业务跳转到对应的静态页面,返回业务需要的数据

        SpringBoot生成二维码并扫码


        结束 ★★★★★

VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]