ImageIO.read(InputStream)返回null

时间:2013-02-21 11:24:26

标签: inputstream derby bufferedimage

我遇到了一个无法找到解决方案的问题。所以请大家阅读这篇文章。请帮助我。

我将图像文件从“.png”文件保存为apache derby db作为Blob格式。保存文件没有任何问题。

要从derby读回来,我首先将数据作为Blob获取,然后将它们转换为InputStream,然后使用以下代码将其存储到我创建的类“Person”对象中

Blob patientPhoto = rs.getBlob("photo");

person.setPhoto(patientPhoto.getBinaryStream());

班级人员概述如下所示

 Public class Person {
    private String personName;
    private InputStream photo;

public void setPhoto(InputStream photo){
        this.photo = photo;
    }
Public InputStream getPhoto(){
    return photo;
    }
 }

最初,我在德比中存储了四个人物对象和图像。然后我从德比中检索这四个人对象并将它们存储到Vector数组中。我从矢量数组中开始逐个显示它们,如下所示

方法-1:来自矢量数组的人物对象的初始化方法

Person data = new Person();

int i=0;

data = vector[i++];

方法-2:人物照片的显示方法

InputStream img = data.getPhoto();

// The image recieved from db should be buffered as it is not real file
// but bytes of streams

BufferedImage buffImg = null
    if(img!=null){
      try {
        buffImg = ImageIO.read(img);
      } catch (IOException e) {
         e.printStackTrace();
      }

    //a panel with JLabel where Image will be displayed

    pnlImg.setImage(buffImg);
    }

try {
    img.close();
    } catch (IOException e) {
      e.printStackTrace();
    }

从索引0到3的向量数组中检索的所有四张照片都显示正常,但是当我尝试将人物对象从向量索引2向后反转到0时,则抛出空指针异常。 代码ImageIO.read(img);当“img”不为null时返回null值。

我无法理解为什么它显示为null而“img”不为null。从矢量索引0到3,它工作,然后向后,它没有。请帮帮我

2 个答案:

答案 0 :(得分:1)

我相信Blob的InputStream仅在您当前定位在该记录上时才有效。因此,您不应期望从getBinaryStream()获得的值将在很长一段时间内保持有效。

相反,应用程序应该在获得blob后立即从流中读取字节数, 然后你可以前进到结果集中的下一条记录。

因此,更改Photo类,以便setPhoto()方法将InputStream中的数据读入其自己的字节数组,然后当调用getPhoto()时,您可以将自己的ByteArrayInputStream返回到Photo的私有字节数组

答案 1 :(得分:0)

我知道这是一篇过时的文章,但是如果您遇到类似的问题,可以尝试一下。我也遇到了类似的问题,并且可以通过以下方式解决。因此,您可以将Person类更改为:

Public class Person {
    private String personName;
    private BufferedImage photo;

    public void setPhoto(BufferedImage photo){
        this.photo = photo;
    }
    public BufferedImage getPhoto(){
        return photo;
    }

}

然后从blob中读取时,只需将Inputstream转换为BufferedImage,然后再将其设置为person对象,如下所示:

Blob patientPhoto = rs.getBlob("photo");
InputStream ins = patientPhoto.getBinaryStream();
person.setPhoto(ImageIO.read(ins));