【问题标题】:ImageIO.read(InputStream) returns nullImageIO.read(InputStream) 返回 null
【发布时间】:2019-05-23 05:01:04
【问题描述】:

我遇到了一个我找不到解决方案的问题。所以请求所有阅读本文的人。请在这方面帮助我。

我将图像文件从“.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;
    }
 }

最初,我将四个 Person 对象与图像一起存储在 derby 中。然后我从 derby 中检索这四个人对象并将它们存储到 Vector 数组中。我通过从向量数组中获取它们开始一一显示,如下所示

方法一:向量数组中人物对象的初始化方法

Person data = new Person();

int i=0;

data = vector[i++];

方法二:人物照片的显示方法

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 而“img”不为 null。从矢量索引 0 到 3 时,它工作,然后向后退,它不工作。请帮帮我

【问题讨论】:

    标签: inputstream derby bufferedimage


    【解决方案1】:

    我相信 Blob 的 InputStream 仅在您当前位于该记录上时才有效。所以你不应该期望你从 getBinaryStream() 得到的值会在很长一段时间内保持有效。

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

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

    【讨论】:

    • 非常感谢您的回复。我只是按照你的建议使用 ByteArrayInputStream 但同样的问题。我再次调试代码,这次我在 Method-2 中检查 InputStream 的可用性,如下所示。 int i = img.available();当我第一次读取 InputStream img [从 getPhoto() 收到时] 时,此代码显示了一些数字。但第二次 img.available() 显示 0。虽然调试代码手表我可以看到缓冲区不是空的。我无法理解问题所在。为什么第二次阅读会消失所有数据。
    【解决方案2】:

    我知道这是一篇旧帖子,但如果您遇到类似问题,您可以试试这个。我也有类似的问题,并且能够以以下方式解决。因此,您可以将类 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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-08
      • 2016-05-28
      • 2021-12-15
      • 2012-04-14
      相关资源
      最近更新 更多