尝试使用Java中的ImageIO.read从oracle DB读取图像blob无法正常工作

时间:2018-03-30 15:38:18

标签: java oracle image blob javax.imageio

我有一些图像存储在oracle DB中作为blob。我想阅读它们并在JLabel中显示。阅读完之后,我尝试使用ImageIO.read,但它总是返回null。请参阅下面的代码:

Blob blob = rs.getBlob(2);
BufferedImage frontImg = ImageIO.read(blob.getBinaryStream());
lblFrontImage.setIcon(new ImageIcon(frontImg));

我可以使用以下代码将图像保存到文件中,因此我知道图像有效:

Blob blob = rs.getBlob(2);
InputStream in = blob.getBinaryStream();
OutputStream out = new FileOutputStream("test.jpg");
byte[] buff = new byte[4096];  
int len = 0;
while ((len = in.read(buff)) != -1) {
   out.write(buff, 0, len);
}
out.close();

我试图在JLabel中显示图像的其他方式

byte[] frontBytes = rs.getBytes(2);
BufferedImage frontImg = ImageIO.read(new 
ByteArrayInputStream(fileContent));
lblFrontImage.setIcon(new ImageIcon(frontImg));

byte[] frontBytes = rs.getBytes(2);
BufferedImage image;
ByteArrayInputStream bis = new ByteArrayInputStream(frontBytes);
image = ImageIO.read(bis);
bis.close();
lblFrontImage.setIcon(new ImageIcon(image));

另外

InputStream in = blob.getBinaryStream();
image = ImageIO.read(in);
byte[] frontImgBytes = blob.getBytes(1, (int) blob.length());
System.out.println("front bytes length: ====\n" + frontImgBytes.length);
BufferedImage frontImage = ImageIO.read(new 
ByteArrayInputStream(frontImgBytes));
lblFrontImage.setIcon(new ImageIcon(frontImage));

尝试了很多方法,继续获得java.lang.NullPointerException。没有其他例外或错误。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

我终于意识到这是因为图像是TIFF图像。我无法使用默认的ImageIO库。我在这里注意到另一个StackOverflow线程Can't read and write a TIFF image file using Java ImageIO standard library,并使用了你的12monkeys库@haraldK,它工作得很好。非常感谢。