我在开发一个数据库应用程序,其中我正在将图像插入到数据库中。我将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. DiazPhoto
类中处理流的代码吗? - Mick Mnemonic