简体   繁体   中英

How can i get the width and height of an image in java using intelij idea?

I have written the following java class

public class main {

    private static BufferedImage image;

    private static String srcImageName = "HeatMap.png";

    public static void main(String[] args) {

        initializeImage();
        System.out.println(image.getWidth());

    }

    private static void initializeImage(){

        image = null;
        try {
            image = ImageIO.read(new File(srcImageName));
        } catch (IOException e) {
            System.out.println("Cannot read image "+ srcImageName);
            //e.printStackTrace();
        }
    }
}

Now my file structure is like so:

  • The main.java file
  • The HeatMap.png file

Both of these are in the same folder. The problem is that when i run the program i get the following response :

Cannot read image HeatMap.png

This tells me that he does not see the image which i cannot figure out why.

Please help.

Both of these are in the same folder. Try

BufferedImage image = ImageIO.read(getClass().getResourceAsStream("HeatMap.png"));

int w = image.getWidth();

int h = image.getHeight();

You can try other options also. Read comments.

// Read from same package 
ImageIO.read(getClass().getResourceAsStream("c.png"));

// Read from absolute path
ImageIO.read(new File("E:\\SOFTWARE\\TrainPIS\\res\\drawable\\c.png"));

// Read from images folder parallel to src in your project
ImageIO.read(new File("images\\c.jpg"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM