繁体   English   中英

如何使用Java从JTable中的MySQL检索blob类型的图像?

[英]How to retrieve image of type blob from MySQL in JTable using Java?

我创建了一个简单的应用程序来显示数据库中的图像。 我在MySQL数据库中有一个表,其列类型为BLOB

当我从表中检索图像时,它仅包含:“ javax.swing.ImageIcon@2143ca6”。

我的代码:

String[] columntabelNames = {"Images"};
DefaultTableModel modelas = new DefaultTableModel(columntabelNames, 0);

Statement stmt = null;
ResultSet rs;

try {
  Connection conn = getConnection();
  stmt = (Statement) conn.createStatement();

  ResultSet rs1;
  rs1 = stmt.executeQuery("SELECT IMAGES_IMAGE FROM dc_images");
  if (rs1.next()) {

    byte[] imgData = rs1.getBytes("IMAGES_IMAGE");
    ImageIcon imagIcon = new ImageIcon(imgData);
    Image im = imagIcon.getImage();
    Image myImage = im.getScaledInstance(50, 50, Image.SCALE_SMOOTH);
    ImageIcon newImageIcon = new ImageIcon(myImage);
    lblimage.setIcon(newImageIcon);

    Object data[] = {newImageIcon};
    modelas.addRow(data);
  }
  tabelImage.setModel(modelas);

} catch (Exception ex) {
  System.out.println(ex.getMessage());
}

尝试这个

Image im = ImageIO.read((ImageInputStream) new DefaultStreamedContent(new ByteArrayInputStream(imgData)));

当我从表中检索图像时,它仅包含:“ javax.swing.ImageIcon@2143ca6”。

JTable的默认渲染器仅在对象上调用toString()方法,因此您将看到ImageIcon的toString()。

您需要重写TableModel (或JTable )的getColumnClass(...)方法以返回Icon.class ,然后该表将使用Icon渲染器。

阅读Swing教程中有关使用渲染器/编辑器的部分,以获取更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM