Getting Height and Width of Image in Java without an ImageObserver

后端 未结 3 1802
无人共我
无人共我 2021-01-19 09:36

I am trying to get the height and width of images (via a url) in Java without an ImageObserver. My current code is:

public static v         


        
相关标签:
3条回答
  • 2021-01-19 10:14

    Following should work

       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 讨论(0)
  • 2021-01-19 10:23

    One can get width and height using following code if there is difficulty in retrieving 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();
      }
    

    Note: data is folder in /src containing images.

    Credit goes to Getting height and width of image in Java

    0 讨论(0)
  • 2021-01-19 10:28

    You can use ImageIcon to handle the loading of the image for you.

    Change

    Image img = Toolkit.getDefaultToolkit().getImage(url);
    sb.append(line + ","+ img.getHeight(null) + "," + img.getWidth(Null) + newline);
    

    to

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

    The main change is to use ImageIcon, and the getIconWidth, getIconHeight methods.

    0 讨论(0)
提交回复
热议问题