Question

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.

Was it helpful?

Solution

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"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top