问题
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.
回答1:
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. :)
回答2:
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).
回答3:
Another alternative I found is to wait until img.getWidth()
returns a value different from -1. You can do this in a cleaner way by using Threads
and while
loops.
来源:https://stackoverflow.com/questions/4260500/how-to-wait-until-an-image-is-fully-loaded-in-java