无法加载BufferedImage [英] Can't load a BufferedImage

查看:94
本文介绍了无法加载BufferedImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有该代码的表格:

I have a form with that code:

public Form() 
{
    initComponents();
    try 
    {
        File file= new File("avatar.jpg");
        BufferedImage image= ImageIO.read(file);
    } 
    catch (IOException ex) 
    {
        System.out.println("Failed to load image");
    }
}

问题在于代码总是抛出IOException并进入catch块.
因此无法读取该文件.
我已经使用Netbeans 7.2创建了项目,目录如下所示:

The problem is that the code always throws the IOException and enters in the catch block.
So the file isn't read.
I have created the project with Netbeans 7.2, and the directory looks like this:

出什么问题了?也许该文件不应该存在于父目录中?还是什么?

What's the problem? Maybe the file shouldn't be there but in the father directory? Or what?

推荐答案

您的图片是否打包在jar中?为了找到答案,像提取一个普通的zip文件一样解压缩jar文件,并检查图像是否在其中(通常位于 jarname \ packagename \ filename 中.如果是,则需要解压缩)

Is your image being packaged within your jar? to find this out, extract you jar file like you would an ordinary zip file and check if the image is anywhere there (normally located by jarname\packagename\filename. If so then you'll need to extract your image as a resource using getResourceAsStream().

那会是这样的:

public class Test {
  private static final String absName = "/yourpackage/yourimage.jpg";

  public static void main(String[] args) {
    Class c=null;
    try {
      c = Class.forName("yourpackage.Test");//pkg is the package name in which the resource lies
    } catch (Exception ex) {
      // This should not happen.
    }
    InputStream s = c.getResourceAsStream(absName);
    // do something with it.
  }

    public InputStream getResourceAsStream(String name) {
      name = resolveName(name);
      ClassLoader cl = getClassLoader();
      if (cl==null) {
        return ClassLoader.getSystemResourceAsStream(name); // A system class.
      }
      return cl.getResourceAsStream(name);
    }

    public java.net.URL getResource(String name) {
      name = resolveName(name);
      ClassLoader cl = getClassLoader();
      if (cl==null) {
        return ClassLoader.getSystemResource(name);  // A system class.
      }
      return cl.getResource(name);
    }

    private String resolveName(String name) {
      if (name == null) {
        return name;
      }
      if (!name.startsWith("/")) {
        Class c = this;
        while (c.isArray()) {
          c = c.getComponentType();
        }
        String baseName = c.getName();
        int index = baseName.lastIndexOf('.');
        if (index != -1) {
          name = baseName.substring(0, index).replace('.', '/') + "/" + name;
        }
      } else {
        name = name.substring(1);
      }
      return name;
    }
}

参考:

这篇关于无法加载BufferedImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆