我怎样才能获得图像的高度和宽度? [英] How can I get height and width of an image?
本文介绍了我怎样才能获得图像的高度和宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么code以下位返回身高:-1,这意味着高度尚不得而知。如何获取图像的高度?
{尝试
//创建图像的位置的URL
网址URL =新的URL(http://bmw-2006.auto-one.co.uk/wp-content/uploads/bmw-m3-2006-3.jpg); //获取图像
java.awt.Image中的图像= Toolkit.getDefaultToolkit()的createImage(URL)。 的System.out.println(高度:+ image.getHeight(NULL));
}赶上(MalformedURLException的E){
}赶上(IOException异常五){
}
解决方案
使用 ImageIO.read(文件/ URL)
来代替。这将阻止同时加载,并返回后,图像的宽度/高度将是已知的。
例如
进口java.awt.image.BufferedImage中;
进口的javax.swing *。
进口javax.imageio.ImageIO中;
进口的java.net.URL;类SizeOfImage { 公共静态无效的主要(字串[] args)抛出异常{
网址URL =新的URL(
http://bmw-2006.auto-one.co.uk/+
的wp-content /上传/宝马m3-2006-3.jpg);
最终的BufferedImage BI = ImageIO.read(URL);
最终字符串大小= bi.getWidth()+X+ bi.getHeight();
SwingUtilities.invokeLater(Runnable的新(){
公共无效的run(){
JLabel的L =新的JLabel(
尺寸,
新的ImageIcon(BI),
SwingConstants.RIGHT);
JOptionPane.showMessageDialog(NULL,L);
}
});
}
}
另外,添加一个媒体跟踪
的图像正在由异步加载工具包
和等待,直到它完全加载
Why is the following bit of code returns Height: -1 which means that the height is yet not known. How to get height of the image?
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) {
}
解决方案
Use ImageIO.read(File/URL)
instead. It will block while loading, and the image width/height will be known after it returns.
E.G.
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(
"http://bmw-2006.auto-one.co.uk/" +
"wp-content/uploads/bmw-m3-2006-3.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);
}
});
}
}
Alternately, add a MediaTracker
to the image being loaded asynchronously by the Toolkit
and wait until it is completely loaded.
这篇关于我怎样才能获得图像的高度和宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文