0

我正在使用一个数据库,其中的图像存储为 byte[]。我编写了这个函数来从 byte[] 数据中获取图像。文件名正确且数据不为空。

public void convert(String fileName , byte[] data) throws IOException
    {   
    File myFile =  new File(fileName);
    System.out.println("filename is " + file);
    ByteArrayInputStream baisData = new ByteArrayInputStream(data);
    BufferedImage imag= ImageIO.read(baisData);
    if(imag == null)
    {
        System.out.println("imag is empty");
    }
    ImageIO.write(imag, "jpg", myFile);
    System.out.println("Image file written successfully");
}

但是当我运行这段代码时,我得到了这个输出。

filename is C:\Users\Abhishek\Desktop\Eclipse\try\i1.jpg
imag is empty
Exception in thread "main" java.lang.IllegalArgumentException: image == null!
  at javax.imageio.ImageTypeSpecifier.createFromRenderedImage(ImageTypeSpecifier.java:925)
  at javax.imageio.ImageIO.getWriter(ImageIO.java:1591)
  at javax.imageio.ImageIO.write(ImageIO.java:1520)
  at TempConvert.convert(TempConvert.java:32)
  at TempConvert.main(TempConvert.java:60)

请告诉我“imag”对象为空的原因可能是什么,以及我应该怎么做才能完美地运行我的代码。提前致谢。

4

2 回答 2

1

你说你知道data包含JPEG数据,你想输出JPEG数据。然后它会更快,并且会产生更好的质量作为奖励,用以下代码替换您的代码:

public void convert(String fileName , byte[] data) throws IOException {   
    File myFile =  new File(fileName);
    System.out.println("filename is " + file);
    OutputStream out = new FileOutputStream(myFile);
    try {
        out.write(data); // Just dump the database content to disk
    }
    finally {
        out.close();
    }
    System.out.println("Image file written successfully");
}
于 2013-10-20T20:32:00.203 回答
0

你的image对象是null. 我认为您的byte[] data.

更改您的 if 条件,如下所示

if(imag != null)
{
    ImageIO.write(imag, "jpg", myFile);
    System.out.println("Image file written successfully");
}else{
    System.out.println("imag is empty");
}
于 2013-10-20T11:58:19.123 回答