1

I can't load image into BufferedImage Object with new File() without full path of the image.

When i'm trying to load an image.png into BufferedImage Object with new File() I face to results:

  1. Success - when I write the whole path (C://Users//benja//Desktop/...) it works fine
  2. Fail - when i write the path of the image that i have imported into my project. Is there a way to make it work even if i'm using new File(...)?
    public class PicturePanel extends JPanel {

    BufferedImage image=null;

    public PicturePanel() {
        try {
            image = ImageIO.read(new 

            /*Works fine with full path: */
            File("C://Users//benjamin//Desktop//Pictures//whiteFish.png"));

            /*fail - throw an exception: */
            //image = ImageIO.read(new 
            File("//RandomThingsInGui/whiteFish.png"));

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

        repaint();
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0,0,500,250,null);
    }   

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.add(new PicturePanel());
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setSize(600,400);
        f.setVisible(true);
    }

What i need is to know if there is a way (and how) to load the image from an imported path (I mean from inside eclipse) or when I use new File(...) I must use full path.

thanks for helpers :)

Benny
  • 488
  • 5
  • 18
  • try this solution . https://stackoverflow.com/questions/9544737/read-file-from-assets – VSB Apr 08 '19 at 15:13
  • can u try removing the first `//` in `//RandomThingsInGui` and see if that works. Also in which path the RandomTings Folder is located. – M.Waqas Pervez Apr 08 '19 at 15:15
  • Possible duplicate of [How do I load a file from resource folder?](https://stackoverflow.com/questions/15749192/how-do-i-load-a-file-from-resource-folder) – Progman Apr 08 '19 at 18:40

1 Answers1

2

Copy the 'whiteFish.png' file to the 'RandomThingsInGui' directory. Can you try this?

try {
    // AS-IS
    //image = ImageIO.read(new File("//RandomThingsInGui/whiteFish.png"));

    // TO-BE (replace '//' to '/')
    image = ImageIO.read(new File("/RandomThingsInGui/whiteFish.png"));
} catch (IOException e) { 
    e.printStackTrace();
}
Madplay
  • 1,027
  • 1
  • 13
  • 25
  • Can you try to move the file to the result of ```System.getProperty("user.dir")``` ? I mean, ```new File(System.getProperty + "/" + your file name)``` – Madplay Apr 10 '19 at 16:29