JFileChooser图像到缓冲图像

时间:2016-04-14 05:26:06

标签: java swing jfilechooser javax.imageio

我在运行程序时遇到了一些问题。基本上我的程序的第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有关,但我不确定。有任何想法吗?谢谢!

2 个答案:

答案 0 :(得分:3)

您似乎永远不会真正打开文件选择器,因此没有选择会占用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了解详情

答案 1 :(得分:-2)

试试这个

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