我正在创建一个返回图像的宽度和高度的方法。 这是一个普通的 32x32 图标。这是我到目前为止所做的:
Image icon;
String filename = "G:\\icon.jpg";
int iconWidth = 0;
int iconHeight = 0;
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
JFrame window = new JFrame();
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
代码输出
-1
32
32 是图像的正确宽度。但为什么它首先返回-1呢?代码完全相同。删除“JFrame”行会使其返回两个 -1。 JFrame 会影响默认工具包吗?
我也尝试过这段代码:
JFrame window = new JFrame();
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
它也返回-1。我根本不明白为什么我必须调用它两次才能得到正确的结果。
最佳答案
来自 getWidth
的文档:
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.
所以也许图像仍在异步加载。尝试使用 ImageObserver,以便在信息可用时您可以收到通知。
关于java - 读取图像宽度和高度的非常奇怪的问题(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6160686/