4

我正在尝试在没有 ImageObserver 的情况下在 Java 中获取图像的heightwidth(通过 url)。我目前的代码是:

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();
}

当我进入调试模式时,我可以看到图像已加载并且我可以看到图像的heightwidth,但我似乎无法返回它们。getHeight()and方法需要一个 Image Observer,而getWidth()我没有。先感谢您。

4

3 回答 3

10

您可以使用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);

主要变化是使用ImageIcon, 和getIconWidth,getIconHeight方法。

于 2010-07-26T16:02:34.910 回答
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);
于 2010-07-26T16:03:44.843 回答
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();
  }

注意: 数据是 /src 中包含图像的文件夹。

归功于在 Java 中获取图像的高度和宽度

于 2013-08-13T08:30:49.920 回答