我在tomcat服務器上有下面的代碼。目標是以.jpg保存圖像(以字符串形式發送)並創建等效的縮略圖。 雖然目標已經實現,但我注意到在每次執行時(甚至在嘗試將幾乎所有使用的變量設置爲「null」之後),服務器memomy增加了6兆字節,永遠不會釋放。由於我有一個非常小的RAM服務器,這確實有問題。順便發送的圖像只有接近30千字節。在java中泄漏圖像處理代碼
public boolean saveImage(String picInString)
throws IOException {
byte[] bytes = null;
try {
bytes = Base64.decode(picInString);
} catch (Base64DecodingException e) {
e.printStackTrace(System.out);
}
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
Iterator<?> readers = ImageIO.getImageReadersByFormatName("png");
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
Graphics2D g2 = null;
try {
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
Image image = reader.read(0, param);
// got an image file
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null),
image.getHeight(null), BufferedImage.TYPE_INT_RGB);
// bufferedImage is the RenderedImage to be written
g2 = bufferedImage.createGraphics();
g2.drawImage(image, null, null);
ImageIO.write(bufferedImage, "jpg", new File("/image.jpg"));
ImageIO.write(Scalr.resize(MyImageClass.cropImage(bufferedImage), 100, 100),
"jpg", new File("/image_mini.jpg"));
bufferedImage.flush();
bufferedImage = null;
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
if (reader != null) {
reader.dispose();
}
if (g2 != null) {
g2.dispose();
}
bis.close();
iis.close();
reader = null;
bis = null;
iis = null;
}
return false;
}
任何幫助將不勝感激!
不知道了解@Boggartfly ...我也檢查了你的鏈接... – user3793589 2015-02-06 03:53:05
老兄,這是一個圖書館爲你做的工作!它完全回答你所問的問題。 – Boggartfly 2015-02-06 03:55:10