歡歡喜喜用上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生成縮略圖,減輕伺服器壓力到此告一段落,發個博文出來,警示入坑的小夥伴,好用的工具是要付出代價滴