Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until an image is fully loaded in Java

The Java image API assumes asynchronous loading. Various methods take an ImageObserver as a parameter which might get informed once the image is completely loaded.

On the other hand some types of images (e.g. BufferedImages) don't use the ImageObserver and will never call it.

So how would code look that waits until an image is fully loaded?

I'd like to have a method like

public void waitUntilLoaded(Image img){
    ...
}

Which guarantees that the image is completely loaded when it returns.

like image 884
Jens Schauder Avatar asked Feb 25 '23 18:02

Jens Schauder


2 Answers

A good option would be java.awt.MediaTracker. There's a good code example in the API documentation. In short, you create a MediaTracker object to track images for a component, tell it which images you want to track, and then call tracker.waitForID(n) which will block until the specified image has finished loading.

Obviously, you need to keep this out of the event thread--but you knew that. :)

like image 168
eaj Avatar answered Mar 05 '23 23:03

eaj


Use a javax.imageio.event.IIOReadProgressListener and override its imageComplete method instead of an ImageObserver.

This is assuming you can change the code to use a javax.imageio.ImageReader to actually read it (created using one of ImageIO's static methods).

like image 21
Powerlord Avatar answered Mar 05 '23 21:03

Powerlord