Getting Height and Width of Image in Java without an ImageObserver
Asked Answered
S

3

5

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

When i go into debug mode I am able to see that the image was loaded and I can see the height and the width of the image, but i can't seem to return them. The getHeight() and getWidth() methods require an Image Observer, which i don't have. Thank you in advance.

Sri answered 26/7, 2010 at 15:55 Comment(0)
S
11

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.

Shaff answered 26/7, 2010 at 16:2 Comment(1)
Thanks a lot. I realised this and came back to answer the question myself :P. Thanks alot though.Sri
B
2

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);
Blindfold answered 26/7, 2010 at 16:3 Comment(0)
P
0

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

Patinous answered 13/8, 2013 at 8:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.