How do I save image file into java project file location from JFileChooser?

20 Views Asked by At

I am retrieving an image file with the following lines of code...

How do I make sure it ends up in the project file location?

public void run() {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "png"));
    while (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        try {
            File f = fileChooser.getSelectedFile();  
            BufferedImage thisImage = ImageIO.read(f);
        }
    }
}

I assume I am supposed to use ImageIO.write() in some way?? Nothing I have dont works.

Two things I've tried:

Files.copy(f.toPath(), new File(System.getProperty("user.dir")).toPath(), StandardCopyOption.REPLACE_EXISTING);

ImageIO.write(thisImage, "png", f);

1

There are 1 best solutions below

1
On

System.getProperty("user.dir") will return the path for the current working dir. I'm assuming that's what you mean. Then it's just using what you suggested to write the file out.

var workingDir = System.getProperty("user.dir");
var outputfile = new File(workingDir + "/saved.png");
ImageIO.write(yourBufferedImage, "png", outputfile);

Something like that anyway.