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.
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. :)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With