【发布时间】:2015-11-03 00:23:58
【问题描述】:
我正在开发一个将图像插入数据库的数据库应用程序。我将 InputStreams 作为 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)是否正在检索您的任何数据吗? -
您能分享
Photo类中的流处理代码吗? -
@AlexandroSifuentesDíaz 最后一段代码是从 resultSet.getBinaryStream(index) 返回的内容。我把它放在 println 命令中只是为了测试目的。
-
@MickMnemonic public void setInputStream(InputStream inputStream) { this.inputStream = inputStream; } 公共输入流 getInputStream() { 返回输入流;对不起,可怕的格式,仍然得到这个窍门。
-
那些方法并不真正处理流——它们只是一个getter和setter。你在哪里读流?请在问题中包含代码(单击编辑链接)。
标签: java mysql nullpointerexception