简体   繁体   中英

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 .

When I retrieve an image from the table it just contains: "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".

The default renderer for the JTable simply invokes the toString() method on the object so you are seeing the toString() for the ImageIcon.

You need to override the getColumnClass(...) method of your TableModel (or JTable ) to return Icon.class , then the table will use an Icon renderer.

Read the section from the Swing tutorial on Using Renderers/Editor for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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