在 JTable 的单列上显示来自 MySQL 数据库的图像 [英] Displaying images from MySQL database on a single column of JTable

查看:35
本文介绍了在 JTable 的单列上显示来自 MySQL 数据库的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示从 blob 数据类型的 MySQL 数据库中检索的图像.无法弄清楚是什么问题导致图像列显示这样的数据 [B@29b8e4f7 而不是图像图标.

I'm trying to display images retrieve from MySQL database of blob datatype. Could not figure out what is the problem that causes the image column to display data like this [B@29b8e4f7 instead of image icon.

DefaultTableModel model = new DefaultTableModel(new Object[]{
    "image", "item_name", "quantity","price", "category", "color", "size"}, 0){
        @Override
        public Class<?> getColumnClass(int column) {
            switch(column){
                case 0: return ImageIcon.class;
                default: return String.class;
            }
        }
    };

    myTable.setModel(model);

...

         ResultSet rs = database.getRS();

            int columns = rs.getMetaData().getColumnCount();

            while(rs.next()){
                Object[] row = new Object[columns];
                for(int i = 1; i <= columns; i++){                        
                    row[i-1] = rs.getObject(i);

                }
                DefaultTableModel defmodel = (DefaultTableModel) tableItem.getModel();
                defmodel.insertRow(rs.getRow()-1, row);

            }

推荐答案

既然你使用了 preparedstatement.setBlob(1, InputStream); 来存储图像,我不得不假设你存储的是物理的图像文件/格式,而不仅仅是像素数据.

Since you used preparedstatement.setBlob(1, InputStream); to store the image, I have to assume that you stored the physical image file/format and not just the pixel data.

您需要读回此图像格式并将其转换为 Swing/Java 支持的图像格式.

You need to read back this image format and convert to a supported image format for Swing/Java.

首先获取对数据库字段的 Blob 引用...

Start by getting a Blob reference to the database field...

Blob blob = rs.getBlob(1);

一旦你有了一个 Blob,你就可以使用它的二进制 InputStream 并读取数据...

Once you have a Blob, you can use it's binary InputStream and read the data...

BufferedImage image = null;
try (InputStream is = blob.getBinaryStream()) {
    image = ImageIO.read(is);
} catch (IOException exp) {
    exp.printStackTrace();
}

现在,您可以使用 new ImageIcon(image) 将其设为 ImageIcon 并将其放入您的表格模型中...

Now, you can make it an ImageIcon using new ImageIcon(image) and put this within your table model...

这篇关于在 JTable 的单列上显示来自 MySQL 数据库的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆