How to wait until an image is fully loaded in Java

泄露秘密 提交于 2020-05-15 03:10:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!