读取图像宽度和高度的非常奇怪的问题(Java)
我正在制作一个返回图像的宽度和高度的方法。 这是一个普通的 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。我根本不明白为什么我必须调用它两次才能得到正确的结果。
I am making a method that returns the width and height of an image.
It's an ordinary 32x32 icon. Here is what I did so far:
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);
The code outputs
-1
32
32 is the correct width of the image. But why does it first return -1? The code is exactly the same. Removing the "JFrame" line makes it return two -1s. Could the JFrame be affecting the default toolkit?
I also tried this code:
JFrame window = new JFrame();
icon = Toolkit.getDefaultToolkit().getImage(filename);
iconWidth = icon.getWidth(null);
iconHeight = icon.getHeight(null);
System.out.println(iconWidth);
It also returns -1. I simply can't understand why I have to call it twice to get a correct result.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自
getWidth
的文档:所以也许图像仍在异步加载。尝试使用 ImageObserver,以便在信息可用时您可以收到通知。
From the docs for
getWidth
:So perhaps the image is still being loaded asynchronously. Try using an ImageObserver so you can be notified when the information becomes available.