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
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);
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
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.