我正在編寫一個應用程序,它讀取並顯示圖像作爲ImageIcons(在JLabel中),應用程序需要能夠支持jpegs和位圖。Java:讀取圖像並作爲ImageIcon顯示
對於jpegs,我發現將文件名直接傳遞給ImageIcon構造函數可以正常工作(即使是顯示兩個大的jpegs),但是如果我使用ImageIO.read獲取圖像並將圖像傳遞給ImageIcon構造函數,當讀取第二個圖像時(使用與以前相同的圖像),會出現OutOfMemoryError(Java堆空間)。
對於位圖,如果我嘗試通過將文件名傳遞給ImageIcon進行讀取,則不顯示任何內容,但通過使用ImageIO.read讀取圖像,然後在ImageIcon構造函數中使用此圖像可以正常工作。
我從閱讀其他論壇帖子可以理解,這兩種方法對於不同格式的工作原理並不一樣,只能歸結爲java與位圖的兼容性問題,但是有沒有辦法解決我的問題,以便我可以使用對於沒有OutOfMemoryError的位圖和jpeg,同樣的方法?
(我想,以避免增加堆大小如果可能的話!)
的OutOfMemoryError錯誤是由該行觸發:
img = getFileContentsAsImage(file);
和方法的定義是:
public static BufferedImage getFileContentsAsImage(File file) throws FileNotFoundException {
BufferedImage img = null;
try {
ImageIO.setUseCache(false);
img = ImageIO.read(file);
img.flush();
} catch (IOException ex) {
//log error
}
return img;
}
堆棧跟蹤爲:
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space
at java.awt.image.DataBufferByte.<init>(DataBufferByte.java:58)
at java.awt.image.ComponentSampleModel.createDataBuffer(ComponentSampleModel.java:397)
at java.awt.image.Raster.createWritableRaster(Raster.java:938)
at javax.imageio.ImageTypeSpecifier.createBufferedImage(ImageTypeSpecifier.java:1056)
at javax.imageio.ImageReader.getDestination(ImageReader.java:2879)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:925)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:897)
at javax.imageio.ImageIO.read(ImageIO.java:1422)
at javax.imageio.ImageIO.read(ImageIO.java:1282)
at framework.FileUtils.getFileContentsAsImage(FileUtils.java:33)
請發佈一些觸發OutOfMemoryError的示例代碼。 – Thomas 2010-03-30 11:40:20