【问题标题】:How to assign blob image to JLabel如何将 blob 图像分配给 JLabel
【发布时间】:2012-06-07 18:22:30
【问题描述】:

我将访问者的图像和其他详细信息存储到表 tbl_visitor 中。代码如下,

    String string_op="F:\\POSTERS\\Roses\\TROPIC4.png"; 
    File imageFile = new File(string_op);
    FileInputStream fis = new FileInputStream(imageFile);

    String queryVis="insert into tbl_visitor(visitor_name,contact_no," +
            "job_profile,org_name,photo_id_proof,type_of_visitor,date," +
            "extra_people,image) values('"+
            name_of_visitor.getText()+"','"+
            contact_num.getText()+"','"+
            job_profile.getText()+"','"+
            org.getText()+"','"+
            photo_id_num.getText()+"','"+
            type_of_visitor.getSelectedItem().toString()+"','"+
            date_and_time.getText()+"','"+
            tf1.getText()+"','"+
            "fis,(int)imageFile.length()"+"')"; 

现在我想在 JFrame 上显示图像并使用 JLabel 显示图像 但我无法将图像分配给 JLabel。我尝试了以下代码来显示图像,但它给了我错误。

Blob image_vis = rs1.getBlob(10);
image_cap.setIcon(image_vis);

请帮帮我。

【问题讨论】:

  • 嗯,SetIcon方法的参数类型必须是ImageIcon类型。所以我会尝试将 Blob 转换为 ImageIcon。不是 100% 肯定这会起作用,因为我不熟悉 Blob 类。
  • 单个代码行 >400 字符宽?!?您必须有一个非常宽的显示器。为了我们其他人的利益,请在 SO 引入滚动条之前强制换行。

标签: java mysql swing netbeans-7


【解决方案1】:

如果您花一些时间阅读 API 文档,这很简单:

Blob 有一个 getBinaryStream(),它返回一个字节流,其中包含存储在 Blob 中的数据。

实现了 Icon 的 ImageIcon 有一个 constructor,它接受一个字节数组作为参数。

JLabel 有一个setIcon(Icon) 方法。

因此,将 Blob 二进制流中的所有内容读入一个字节数组,使用该字节数组构造一个 ImageIcon,并以该 ImageIcon 作为参数调用标签 setIcon 方法。

【讨论】:

  • 感谢您的解决方案。您能否通过编码详细说明这些陈述?提前致谢。
  • 我不会为你做任何事,不。谷歌“Java IO 教程”了解如何从输入流读取到字节数组,或使用 Guava 为您完成。剩下的就是三行代码了。
  • T 试过这段代码,但它不显示 imageBlob image_vis = rs1.getBlob(10); ObjectInputStream ois = null; ois = new ObjectInputStream(image_vis.getBinaryStream()); ImageIcon image = (ImageIcon) ois.readObject();
  • 我的回答根本没有告诉你这样做。它说:将 Blob 二进制流中的所有内容读入字节数组使用这个字节数组构造一个 ImageIcon(我什至链接到你必须使用的构造函数)。您的代码假定您在 blob 中存储了一个序列化的 ImageIcon 对象,但事实并非如此。真的有那么难吗?这是您需要的全部代码(使用 Guava):label.setIcon(new ImageIcon(ByteStreams.toByteArray(blob.getBinaryStream())));
猜你喜欢
  • 2015-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-13
  • 2017-06-18
  • 2021-09-25
  • 1970-01-01
  • 2013-09-22
相关资源
最近更新 更多