简体   繁体   中英

What is the purpose of the ImageObserver field when getting the height and width of an image?

Java has this method: getWidth(ImageObserver observer)

It returns the Width of an image. This method seems simple enough until you get to the part where an ImageObserver is requiered. What is the purpose of the ImageObserver as a parameter. Is there any other way around this?

Note that I can't just use an ImageIcon as mentioned here: Getting Height and Width of Image in Java without an ImageObserver The reason is because I will ultimately be loading my image from a JFileChooser. This is also why I can't just use constants for the Height and Width. I don't know which picture the user will be wanting to use.

Also, I don't feel like I should post my code for these two reasons

A) My code is not anywhere close to being a SSCCE piece of code: http://sscce.org/

B) This is such a general question that I feel my code would be too specific.

From the JavaDocs

Determines the width of the image. If the width is not yet known, this method returns -1 and the specified ImageObserver object is notified later.

This basically means that if the Image is not fully realised (as it is generally loaded in a background thread), the ImageObserver will be notified when the value is known.

A better solution would be to make use of the ImageIO API as the read method won't return until the image is fully loaded (and realised) or throws a IOException if the image can't be loaded.

Have a look at Reading/Loading an Image for more details

If you "really" have to use Image and Toolkit to load them, then you should also have a look at MediaTracker , but since BufferedImage (which is returned by ImageIO.read ) extends Image , there really isn't much need

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM