将图像blob插入MySQL - 空指针异常

5

我在开发一个数据库应用程序,其中我正在将图像插入到数据库中。我将InputStream作为BLOB存储在数据库中,并且在检索它们并将它们设置为ImageIcon时遇到了问题。

try{
    // Return a resultset That contains 
    // the photos from the hashtags the user is following.

    preparedStatement = conn.prepareStatement("SELECT * FROM PHOTOS WHERE CARID=?");
    preparedStatement.setInt(1, 1);
    resultSet = preparedStatement.executeQuery();
    while(resultSet.next()){
        newPhoto = new Photo(resultSet.getInt(1), resultSet.getInt(2), 
                             resultSet.getLong(3), resultSet.getBinaryStream(4));
        System.out.println(resultSet.getBinaryStream(4));
        photos.add(newPhoto);
        System.out.println("Retrieving a photo");
    }
}

photos是使用我的Photo类返回的ArrayList。每次我尝试显示图片时,都会出现以下错误...

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at business.appdev.Home.paintEditFrame(Home.java:577)

这是来自以下代码的:

...


editImageLabel[i].setIcon(
        new ImageIcon(img.getScaledInstance(imageSize, imageSize, imageSize)));

我有一些基本的println命令,可以显示从MySQL数据库返回的内容,即

java.io.ByteArrayInputStream@2c0213a5
Retrieving a photo
java.io.ByteArrayInputStream@252ab7be
Retrieving a photo

其中img是BufferedImage。非常感谢您的帮助!

用于处理resultSet返回的InputStream的代码。

for(int i = 0; i < photos.size(); i++){         
img = ImageIO.read(photos.get(i).getInputStream());
editImageLabel[i] = new JLabel("");
editImageLabel[i].setIcon(new ImageIcon(img.getScaledInstance(imageSize, imageSize, imageSize)));

使用byte[]数据更新了Photo类 根据我阅读的一些其他帖子,我将byte[]存储到MySQL的varbinary中。之后,我使用该方法从数据库中获取照片数据:

InputStream in = resultSet.getBinaryStream(4);
byte[] photoData = new byte[(int) resultSet.getLong(3)];
ByteArrayOutputStream os = new ByteArrayOutputStream();
for (int len; (len = in.read(photoData)) != -1;)
    os.write(photoData, 0, len);
    os.flush();

我接着创建了我的照片对象,并返回一个照片ArrayList。这样就避免了NullPointerException,但现在我无法让ImageIcon JLabels显示出来。我使用以下代码将它们添加到JPanel中,

InputStream in = new ByteArrayInputStream(photos.get(i).getData());
BufferedImage newImage = ImageIO.read(in);
editImageLabel[i] = new JLabel("");
editImageLabel[i].setIcon(new ImageIcon(newImage.getScaledInstance(imageSize, imageSize, Image.SCALE_DEFAULT)));

然后我将标签放在JPanel上。


你能检查一下 resultSet.getBinaryStream(index) 是否能够获取到任何数据吗? - Alex S. Diaz
1
你能分享一下你的Photo类中处理流的代码吗? - Mick Mnemonic
@AlexandroSifuentesDíaz 最后的代码部分是从resultSet.getBinaryStream(index)返回的。我只是为了测试目的将它放在println命令中。 - Chris Davis
这些方法并没有真正处理流 -- 它们只是一个 getter 和一个 setter。你从哪里读取流?请在问题中包含代码(点击编辑链接)。 - Mick Mnemonic
@MickMnemonic的代码已添加。上传文件时,图片将显示,在从数据库检索并尝试显示它们时出现了NullPointer。 - Chris Davis
显示剩余4条评论
1个回答

0
避免编码和解码图像的麻烦,通过将图像存储在文件系统中并仅在数据库中存储图像路径来解决问题。这可以帮助减小数据库大小,从而提高事务效率。您可以编写一些快速代码,在服务器上为文件生成数字文件名。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接