【问题标题】:Getting Height and Width of Image in Java without an ImageObserver在没有 ImageObserver 的情况下在 Java 中获取图像的高度和宽度
【发布时间】:2011-03-21 04:14:14
【问题描述】:

我正在尝试在没有 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()getWidth() 方法需要 Image Observer,而我没有。提前谢谢你。

【问题讨论】:

    标签: java image-processing awt dimensions


    【解决方案1】:

    您可以使用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,以及getIconWidthgetIconHeight方法。

    【讨论】:

    • 非常感谢。我意识到了这一点,然后自己回来回答这个问题:P。不过非常感谢。
    【解决方案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);
    

    【讨论】:

      【解决方案3】:

      如果检索 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 中包含图片的文件夹。

      归功于Getting height and width of image in Java

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-25
        • 1970-01-01
        • 2013-03-16
        • 2014-09-13
        • 2016-10-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多