在Java中获取图像的高度和宽度,无需使用ImageObserver

5

我正在尝试在Java中获取图像(通过URL)的高度宽度,而不需要使用ImageObserver。

我的当前代码如下:

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub

    File xmlImages = new File("C:\\images.xml");
    BufferedReader br = new BufferedReader(new FileReader(xmlImages));
    File output = new File("C:\\images.csv");
    BufferedWriter bw = new BufferedWriter(new FileWriter(output));
    StringBuffer sb = new StringBuffer();
    String line = null;
    String newline = System.getProperty("line.separator");
    while((line = br.readLine()) != null){
        if(line.contains("http")){
            URL url = new URL(line.)
            Image img = Toolkit.getDefaultToolkit().getImage(url);
            sb.append(line + ","+ img.getHeight(null) + "," + img.getWidth(Null) + newline);            
        }

    }

    br.close();
    bw.write(sb.toString());
    bw.close();
}

当我进入调试模式时,我能够看到图片已经加载,并且我可以看到图片的高度和宽度,但我似乎无法返回它们。 getHeight()getWidth() 方法需要一个图像观察者,而我没有。预先感谢您。
3个回答

11
你可以使用ImageIcon来处理图片的加载。
修改
Image img = Toolkit.getDefaultToolkit().getImage(url);
sb.append(line + ","+ img.getHeight(null) + "," + img.getWidth(Null) + newline);

ImageIcon img = new ImageIcon(url);
sb.append(line + ","+ img.getIconHeight(null) + "," + img.getIconWidth(Null) + newline);

主要变化是使用ImageIcongetIconWidthgetIconHeight方法。

1
非常感谢。我意识到了这一点,回来自己回答问题了 :P。还是非常感谢你。 - Bilzac

2

以下操作应该有效:

   Image image = Toolkit.getDefaultToolkit().getImage(image_url);
   ImageIcon icon = new ImageIcon(image);
   int height = icon.getIconHeight();
   int width = icon.getIconWidth();
   sb.append(line + ","+ height + "," + width + newline);

0
如果在检索URL时有困难,可以使用以下代码获取宽度和高度。
try {

File f = new File(yourclassname.class.getResource("data/buildings.jpg").getPath());
BufferedImage image = ImageIO.read(f);
int height = image.getHeight();
int width = image.getWidth();
System.out.println("Height : "+ height);
System.out.println("Width : "+ width);
              } 
catch (IOException io) {
    io.printStackTrace();
  }

注意:data是包含图像的/src文件夹。

感谢在Java中获取图像的高度和宽度的贡献。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接