Extreme Coders
Extreme Coders

Reputation: 3511

Lazily loading images in Java

Let us consider this code snippet

Image img=Toolkit.getDefaultToolkit().getImage("1.png");
g.drawImage(img,0,0,null);

What the code does is load the image 1.png and draw it on a graphic context. Now what I observe is drawImagedo not draw any image the first time it is called. Instead it draws the image on further calls. Now I think this behavior is due to asynchronous image load or the lazy behavior of the method.

To correct the problem what I could do is use the javax.swing.ImageIcon class like this.

Image img=new ImageIcon("1.png").getImage();
g.drawImage(img,0,0,null);

I want to know what are the other better ways to perform the same task.

Upvotes: 3

Views: 3180

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

It depends.

If you are loading the image over a "slow" connection (like the internet) or you are loading a sizable image, it's best to use a lazy loading approach.

This allows the application to continue running while the image is begin loaded.

Andrew is correct, you should be using g.drawImage(img,0,0,this), as this allows the component to automatically update itself once the image has completed loading, without you needing to perform any other actions.

If you application relies on the image for some part of it's operation OR you are loading small images locally, it would be sufficent to use something like...

BufferedImage image = ImageIO.read(imageResource); 
// Where image resource is either a file or local URL (such as an embedded resource)

I personally, tend to use a background thread to load my images in most cases and use ImageIO. In my paint method, I might use a small placeholder image if required to let the user know that I am loading the image.

You will also need to take into consideration the type of image you are loading as well. While ImageIO has a larger support for image formats, loading animated GIFs is problematic and requires significant more work on you part to achieve.

ps - Don't load images in you component paint methods - paint can be called numerous times and loading images (or other resources) will dramatically slow the repaint process, making your application lag...

Upvotes: 6

user1874520
user1874520

Reputation:

Try using ImageIO.read() for loading the images. This will block until the image is fully loaded. Check this page.

Upvotes: 2

Related Questions