Hutool生成图片二维码 输出到前端

本文介绍如何使用Hutool库在Java环境中生成带有Logo的二维码,并提供了详细的代码示例,包括pom.xml配置、后端代码实现及如何处理Logo图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文档地址

https://hutool.cn/docs/#/extra/%E4%BA%8C%E7%BB%B4%E7%A0%81%E5%B7%A5%E5%85%B7-QrCodeUtil

 

pom引入

 

hutool jar
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.0.7</version>
</dependency>

考虑到Hutool的非强制依赖性,因此zxing需要用户自行引入
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>

编译需要
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
</build>

后端代码

 /**
     * 生成二维码
     * @param content 内容
     * @param logourl  logo
     */
    public void createQrCodeN(String content, String logourl, int width, int height,HttpServletResponse response){
        QrConfig config = new QrConfig(width, height);
        File file = null;
        try {
            file = ResourceUtils.getFile(logourl);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //附带logo
        config.setImg(file);
        // 设置边距,既二维码和背景之间的边距
        config.setMargin(3);
        // 高纠错级别
        config.setErrorCorrection(ErrorCorrectionLevel.H);
        // 设置前景色,既二维码颜色(青色)
        config.setForeColor(new Color(0,60,130).getRGB());
// 设置背景色(灰色)
        config.setBackColor(new Color(242,242,242).getRGB());
       /* try {
            OutputStream  out = new FileOutputStream("");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/

        BufferedImage bufferedImage = QrCodeUtil.generate(//
                content, //二维码内容
                config
        );
        try {
            //以JPEG格式向客户端发送
            ServletOutputStream  os = response.getOutputStream();
            ImageIO.write(bufferedImage, "PNG",os);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

controller

 

 

postman测试

 如果打成jar需要这样读取file

InputStream initialStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(logourl);
byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
File file = new File("src/main/resources/targetFile.tmp");
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值