Rad*_*dek 9 java asynchronous image
为什么下面的代码返回高度:-1表示高度尚未知晓.如何获得图像的高度?
try {
// Create a URL for the image's location
URL url = new URL("http://bmw-2006.auto-one.co.uk/wp-content/uploads/bmw-m3-2006-3.jpg");
// Get the image
java.awt.Image image = Toolkit.getDefaultToolkit().createImage(url);
System.out.println("Height: " + image.getHeight(null));
} catch (MalformedURLException e) {
} catch (IOException e) {
}
Run Code Online (Sandbox Code Playgroud)
And*_*son 15
使用ImageIO.read(URL)或ImageIO.read(File)代替.它会在加载时阻塞,图像宽度和高度在返回后将被知道.
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
class SizeOfImage {
public static void main(String[] args) throws Exception {
URL url = new URL("https://i.stack.imgur.com/7bI1Y.jpg");
final BufferedImage bi = ImageIO.read(url);
final String size = bi.getWidth() + "x" + bi.getHeight();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JLabel l = new JLabel(
size,
new ImageIcon(bi),
SwingConstants.RIGHT );
JOptionPane.showMessageDialog(null, l);
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
或者,添加一个MediaTracker由异步加载的图像,Toolkit并等待它完全加载.