今天图片加水印的小工具时,报如下错误
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