给图片加水印时的错误处理
今天在测试给图片加水印时,出现了这样一个错误:
放上代码:
package com.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 url = "E:\\she said\\life";
String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
Thumbnails.of(new File(url + "\\test.jpg"))
.size(200, 200).watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "\\watermark.png")), 0.25f)
.outputQuality(0.8f).toFile(url + "\\test2.jpg");
}
}
首先翻了一下百度,说到文件的url中的空格可能会出现编码问题,于是输出了一下url:
/E:/she%20said/study/ssm%20exercise/o2o/target/classes/
中间的%20即为空格,把url重新编码就可以解决。
在basepath后加一行:
basePath = URLDecoder.decode(basePath, "utf-8");
url同理,但运行之后还是报上面的错误。
接着去上面的url对应文件夹翻了一下,发现没有这个文件。
将图片文件暴力复制一份到这个文件夹就解决了。
ps:
Thumbnailator项目地址:点击此处跳转
maven依赖:
<!--图片处理-->
<!-- https://mvnrepository.com/artifact/net.coobird/thumbnailator -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
参考博客:
1.https://blog.csdn.net/lmhlmh_/article/details/82886419
2.https://blog.csdn.net/sougou_1323/article/details/89419324