想要将BufferedImage另存为jpg但我的代码将其另存为textfile

时间:2018-07-11 21:22:54

标签: java image jpeg

我想将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();
        }

    }
}

1 个答案:

答案 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();
    }

  }
}