Java Graphics How to - Read Image file and get its size








Question

We would like to know how to read Image file and get its size.

Answer

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
//  w w w  .j  a  va  2  s.c  o  m
import javax.imageio.ImageIO;

public class Main {
  BufferedImage img;

  public static int getWidthFromImage(String filename) {
    BufferedImage image;
    try {
      image = ImageIO.read(new File(filename));
      return image.getWidth();
    } catch (IOException e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
    return -1;
  }

  public static void main(String args[]) {
    System.out.print("The width of the image in pixels is: "
        + getWidthFromImage(args[0]));
  }
}