I want to export a BufferedImage as jpg, but in this code it will get saved as a textfile. How can i fix this?
public void saveImage(BufferedImage im) {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("jpg", ".jpg");
fc.setAcceptAllFileFilterUsed(false);
fc.setFileFilter(filter);
int ret = fc.showSaveDialog(null);
File f = fc.getSelectedFile();
if (ret == JFileChooser.APPROVE_OPTION) {
try {
ImageIO.write(im, "jpg", f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There is not an option on JFileChooser to have it autopopulate the extension if not typed in. You have to check for this after the File is retrieved from the dialog.
public static void saveImage(BufferedImage im) {
JFileChooser fc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("jpg", ".jpg");
fc.setAcceptAllFileFilterUsed(false);
fc.setFileFilter(filter);
int ret = fc.showSaveDialog(null);
File f = fc.getSelectedFile();
if (ret == JFileChooser.APPROVE_OPTION) {
try {
if(!f.getName().endsWith(".jpg"))
{
String name = f.getAbsolutePath() + ".jpg";
f = new File( name );
}
ImageIO.write(im, "jpg", f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}