JFileChooser 图像到缓冲图像

JFileChooser image to buffered image

我在将我的程序升级到 运行 时遇到了一些问题。基本上我程序的第 1 步是使用 JFileChooser 打开图像并将其变成缓冲图像,很简单吧?这就是我所拥有的:

JButton open = new JButton();
            JFileChooser fc = new JFileChooser();
            File selectedFile = fc.getSelectedFile();
            fc.setDialogTitle("Please choose an image...");
            FileNameExtensionFilter filter = new FileNameExtensionFilter("JPEG", "jpeg", "jpg", "png", "bmp", "gif");
            BufferedImage origImage = null;

            String path = "";
            File f = fc.getSelectedFile();
            boolean exists = false;
            fc.addChoosableFileFilter(filter);


            try {

                f = fc.getSelectedFile();
                exists = f.exists();
                path = f.getAbsolutePath();

                origImage = ImageIO.read(new File(path));
            }
            catch(Exception e) {
                System.out.println(e);
                System.exit(0);
            }

我得到一个空指针异常(被我的 catch 语句捕获)我认为它与 getbsolutepath 有关,但我不确定。有任何想法吗?谢谢!

试试这个

path = f.getAbsolutePath().replace("\", "\\");

您似乎从来没有真正打开过文件选择器,因此没有选择任何文件来解释 NullPointerException

JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Please choose an image...");
FileNameExtensionFilter filter = new FileNameExtensionFilter("JPEG", "jpeg", "jpg", "png", "bmp", "gif");
fc.addChoosableFileFilter(filter);

BufferedImage origImage = null;
// You should use the parent component instead of null
// but it was impossible to tell from the code snippet what that was.
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fc.getSelectedFile();
    try {
        origImage = ImageIO.read(selectedFile);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

查看 How to Use File Choosers 了解更多详情