Shi
Shi

Reputation: 520

Linux: How to save a image using ImageIO.write()?

I am writing a screen capture program on Linux using Java. How can I use ImageIO.write() like I used it on windows like:

ImageIO.write(screenshot, "png", new File("c:/output.png"));

Upvotes: 1

Views: 3126

Answers (2)

Jamie
Jamie

Reputation: 4078

If you're writing a screen capture program, then you probably want to use a FileChooser to allow the user to choose where to output the file.

Here's a simple example of how you could implement one:

JFileChooser jfc = new JFileChooser();
int returnVal = jfc.showSaveDialog();

if(returnVal == JFileChooser.APPROVE_OPTION) {
    File outputFile = jfc.getSelectedFile();
    ImageIO.write(screenshot, "png", outputFile);
}

This will also help to make your code fully cross-platform, instead of hard-coding platform-specific paths into the program.

Upvotes: 1

wchargin
wchargin

Reputation: 16047

On Linux there is no "C:\" drive. Instead, your drive is mounted at a mount point (usually /). You could write to your home directory (equivalent of Win7's C:\Users\yourusername\) with either of these:

ImageIO.write(screenshot, "png", new File("/home/yourusername/output.png"));
ImageIO.write(screenshot, "png", new File("~/output.png"));

or to the temp folder (if you have permissions) with:

ImageIO.write(screenshot, "png", new File("/tmp/output.png"));

You could also write to the current directory with a simple:

ImageIO.write(screenshot, "png", new File("output.png"));

To find your drive's mount point, run df -h in a terminal to see all mounted drives.

Upvotes: 2

Related Questions