[英]Java - BufferedImage (ImageIO.Read) OutOfMemory Heap Space
Ok, so I am getting an Out of Memory (Heap Space) error in my code, and I have figured out (with profiling) that the error is coming from the creation of images. 好的,所以我的代码中出现了内存不足(堆空间)错误,并且我发现(带有概要分析)该错误是由于创建图像而引起的。
What I have is a class that creates an image into a smaller one, and then that class will be painted. 我所拥有的是一类,可以将图像创建为较小的图像,然后对该类进行绘制。
The problem is that if I want to load up 1000+ of these images into JPanels, I get to around 750 before it taps out, and I don't really want to extend the memory of java. 问题是,如果我想将这些图像中的1000多个加载到JPanels中,那么在将其提取出来之前,我会达到750个左右,我真的不想扩展Java的内存。
Heres the code: 这是代码:
class Foo extends JPanel{
private BufferedImage image;
private Image scaled;
public Foo(String link){
try{
setPreferredSize(new Dimension(50,50));
image = ImageIO.read(new URL(link)); //Cause for memory leak
scaled= image.getScaledInstance(100, 140, BufferedImage.SCALE_FAST);
image.flush();
//tried image = null; but did not help memory
}
catch(Exception e){}
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(scaled, 5, 5, null);
}
}
So basically, is there a more efficient way to read a link into an image, or some how remove unnecessary memory? 因此,基本上,有没有更有效的方法将链接读取到图像中,或者有一些如何删除不必要的内存?
我不确定这是否足够,但是您可以使用以下方法消除使用scaled
的情况:
drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
Know problem... 知道问题...
You probably don't need to re-read the full images each time. 您可能不需要每次都重新读取完整图像。
I have implemented a similar feature. 我已经实现了类似的功能。 What I do is that I store snapshots of every image at a desired size + I include in the filename the timestamp of this snapshot so that I know if the snapshot is still up-to-date.
我要做的是,以所需的大小存储每个图像的快照+在文件名中包含此快照的时间戳,以便知道快照是否仍是最新的。
This does not solve your problem for the initial snapshot making but well for later uses. 对于最初的快照制作,这并不能解决您的问题,但对于以后的使用来说却很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.