SpringBoot生成二维码并扫码


一、引入依赖

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

<!-- 二维码生成 -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.2.1</version>
</dependency>

二、配置

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<EncodeHintType, String> 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 < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}
}

三、接口测试

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

/**
 * @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<File> 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
在这里插入图片描述
本地正常生成文件
在这里插入图片描述

手机扫码测试

手机扫码需要跟电脑要在同一局域网,电脑直接扫码没有问题
此处的返回结果只是案例,可以根据实际业务跳转到对应的静态页面,返回业务需要的数据

在这里插入图片描述


结束 ★★★★★

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值