Search code examples
javaswingbufferedimageembedded-resourcejavax.imageio

Reading image path with "ImageIO.read" to be displayed in a JLabel


Full local path (C:\\Users\\workspace\\myproject\\src\\eclipse\\mainclass\\icons\\my-image.png) works fine, but using the short path like in the code below, gives an exception javax.imageio.IIOException: Can't read input file!.

What am I doing wrong here?

    JLabel lab_h1 = new JLabel();
    BufferedImage img = null;

    try {
        img = ImageIO.read(new File("icons/my-image.png"));

    } catch (IOException e) {
        e.printStackTrace();
    }

    Image dimg = img.getScaledInstance(140, 40,Image.SCALE_SMOOTH);

    lab_h1.setIcon(new ImageIcon(dimg));

Solution

  • The problem you are having, when you try to open a file with a relative path it looks relative to where you run the program. Instead of hoping to get the path correct, you can use a Resource.

    BufferedImage img = ImageIO.read( 
           YourClassName.class.getResource(
                 "/mainclass/icons/my-image.png"
           ) 
     );
    

    I think you might need to tinker with the path since I don't know what is your package structure. I am also assuming that eclipse will bundle resource files that are in your source folder.