springboot2.* 打成jar包后,访问resources路径下图片,使用生成tmp文件解决方案

问题原因:

springboot项目需要生成带logo的二维码,且logo需要内置在jar包中。 打成jar包后图片无法访问。 报错

java.io.FileNotFoundException: class path resource [logo.jpg] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/*/*/*/*/target/*-2.0.0.jar!/BOOT-INF/classes!/logo.jpg

 

解决方案:

使用ClassPathResource读取文件,并在指定目录重新生成临时文件 代码如下:

 /**
     * 插入LOGO
     *
     * @param source
     *            二维码图片
     * @param logoPath
     *            LOGO图片地址
     * @param needCompress
     *            是否压缩
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
        //读取resources路径下的文件,获取输入流
        ClassPathResource classPathResource=new ClassPathResource(logoPath);
        InputStream inputStream=classPathResource.getInputStream();
        //基于Guava的实现临时文件生成
        byte[] buffer = new byte[inputStream.available()];
        inputStream.read(buffer);
        String jarPath=System.getProperty("user.dir");
        File targetFile = new File(jarPath+logoPath);
        Files.write(buffer, targetFile);
        //文件生成完毕后使用qrcode绘制二维码

        Image src = ImageIO.read(targetFile);
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > LOGO_WIDTH) {
                width = LOGO_WIDTH;
            }
            if (height > LOGO_HEIGHT) {
                height = LOGO_HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值