欢欢喜喜用上thumbnailator,开开心心上了生产,结果服务器用了一两周,突然出现读取不了图片的问题,而且ls都不出来东西,过了一阵子,服务器打印出来一个message,大致内容是内存吃满了。。。。。。由于是生成缩略图那里走不动了,于是开始网上搜罗大量资料,终于找到一个说thumbnailator坏话的了,一看日期,居然是今年8月份的,救星啊,果断舍弃了thumbnailator
论据博文:
https://blog.csdn.net/qq_35551089/article/details/98069904
但是文章中最后给出的方法在我这里也不适用,生成的图片都是黑的,于是找了半天原因,发现是toolkit异步的问题,用上面博文里写的while方法,不能确保图片文件已经被加载
各种搜索和调试过后,上代码看吧
try {
// 使用源图像文件名创建ImageIcon对象。里面使用了toolkit,性能相对IOimage.read稳定,比thumbnailtor占用内存少
ImageIcon imgIcon = new ImageIcon(location);
// 得到Image对象。
Image srcImage = imgIcon.getImage();
// 计算比例
int width = -1;
int height = -1;
int rate = 0;
width = srcImage.getWidth(null); // 得到源图宽
height = srcImage.getHeight(null); // 得到源图长
if (width > 0 && height > 0) {
int rate1 = width / WIDTH;//宽度缩略比例
int rate2 = height / HEIGHT;//高度缩略比例
if (rate1 > rate2) {//宽度缩略比例大于高度缩略比例,使用宽度缩略比例
rate = rate1;
} else {
rate = rate2;
}
} else {
// 防止宽高未获取到,额,显然可能多此一举,图个安心
rate = 1;
width = 200;
height = 200;
}
//计算缩略图最终的宽度和高度
int newWidth = width / rate;
int newHeight = height / rate;
// 定义BufferedImage,后面那个TYPE_INT_RGB网上大多数用这个,所以没管为啥
BufferedImage bufferedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
// 创建Graphics2D对象,用于在BufferedImage对象上绘图。
Graphics2D graphics = bufferedImage.createGraphics();
// 设置图形上下文的当前颜色为白色。
graphics.setColor(Color.WHITE);
// 用图形上下文的当前颜色填充指定的矩形区域。
graphics.fillRect(0, 0, newWidth, newHeight);
// 按照缩放的大小在BufferedImage对象上绘制原始图像。
graphics.drawImage(srcImage, 0, 0, newWidth, newHeight, null);
// 释放图形上下文使用的系统资源。
graphics.dispose();
// 网上很多人说formatname为png生成出来的图片不会有错误,抱着侥幸心理,就写png了,貌似还有gif和jpg这两种可以用
res = ImageIO.write(bufferedImage, "png", new File(targetPath));
srcImage.flush();
bufferedImage.flush();
graphics.dispose();
} catch (Exception e) {
logger.info(">>>>>>>>>>>>>>>>>>>>>>xx生成缩略图错误 " + e.getMessage());
}
至此,java生成缩略图,减轻服务器压力到此告一段落,发个博文出来,警示入坑的小伙伴,好用的工具是要付出代价滴