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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.