想将 BufferedImage 保存为 jpg 但我的代码将其保存为文本文件
Want to save BufferedImage as jpg but my code saves it as textfile
我想将 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();
}
}
}
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();
}
}
}
我想将 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();
}
}
}
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();
}
}
}