我想将BufferedImage导出为jpg,但是在此代码中它将保存为文本文件。我该如何解决?
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();
}
}
}
答案 0 :(得分:0)
如果没有输入,JFileChooser上没有选项可以自动填充扩展名。您必须在从对话框中检索“文件”之后进行检查。
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();
}
}
}