报错 Exception in thread “main“ javax.imageio.IIOException: Can‘t read input file!

本文介绍了一种解决在Java程序中为图片添加水印时出现的读取文件异常问题的方法,通过正确处理文件路径,确保了图片水印功能正常运行。

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

今天图片加水印的小工具时,报如下错误

Exception in thread "main" javax.imageio.IIOException: Can't read input file!
	at javax.imageio.ImageIO.read(ImageIO.java:1301)
	at com.bc.o2o.util.ImageUtil.main(ImageUtil.java:16)

将basePath输出,其结果为:

/F:/java%e7%9b%b8%e5%85%b3%e6%96%87%e4%bb%b6/%e4%bb%8e%e9%9b%b6%e5%bc%80%e5%8f%91%e6%a0%a1%e5%9b%ad%e5%95%86%e5%8a%a1%e5%b9%b3%e5%8f%b0%ef%bc%88idea%ef%bc%89/target/classes/

可见不是我们所需要的路径,这就是报错的原因所在。
添加如下代码即可

basePath = URLDecoder.decode(basePath,"utf-8");

源代码:

package com.bc.o2o.util;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;

public class ImageUtil {
    public static void main(String[] args) throws IOException {
        String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        basePath = URLDecoder.decode(basePath,"utf-8");
        System.out.println(basePath);
        Thumbnails.of(new File("C:/Users/鲍超/Desktop/项目图片/xiaoji.jpg"))
                .size(200,200).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/watermark.jpg")),0.25f)
                .outputQuality(0.8f).toFile("C:/Users/鲍超/Desktop/项目图片/xiaojinew.jpg");

    }
}

参考链接: https://blog.youkuaiyun.com/qq_41279172/article/details/104018617

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值