简体   繁体   English

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

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

I have created a simple application to display images from a database. 我创建了一个简单的应用程序来显示数据库中的图像。 I have a table in a MySQL database with a column of type BLOB . 我在MySQL数据库中有一个表,其列类型为BLOB

When I retrieve an image from the table it just contains: "javax.swing.ImageIcon@2143ca6". 当我从表中检索图像时,它仅包含:“ javax.swing.ImageIcon@2143ca6”。

My code: 我的代码:

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)));

When I retrieve an image from the table it just contains: "javax.swing.ImageIcon@2143ca6". 当我从表中检索图像时,它仅包含:“ javax.swing.ImageIcon@2143ca6”。

The default renderer for the JTable simply invokes the toString() method on the object so you are seeing the toString() for the ImageIcon. JTable的默认渲染器仅在对象上调用toString()方法,因此您将看到ImageIcon的toString()。

You need to override the getColumnClass(...) method of your TableModel (or JTable ) to return Icon.class , then the table will use an Icon renderer. 您需要重写TableModel (或JTable )的getColumnClass(...)方法以返回Icon.class ,然后该表将使用Icon渲染器。

Read the section from the Swing tutorial on Using Renderers/Editor for more information. 阅读Swing教程中有关使用渲染器/编辑器的部分,以获取更多信息。

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

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