如何将 blob 转换为图像以在 Java 中的 JLabel 上显示它?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30751964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:36:06  来源:igfitidea点击:

How to convert blob to image to display it on a JLabel in Java?

java

提问by Aziiee

I have a table "xy" in my MySQL DB in which I have saved an image (.png). What I need is to load the image, convert from blob to image and display it on a JLabel.

我的 MySQL 数据库中有一个表“xy”,我在其中保存了一个图像 (.png)。我需要的是加载图像,从 blob 转换为图像并将其显示在 JLabel 上。

Can anybody help me with converting the image?

有人可以帮我转换图像吗?

Thanks!

谢谢!

回答by Peter Pan

Some Code block, if can help you:

一些代码块,如果可以帮助您:

ResultSet rs = stmt.executeQuery(<Your Query SQL>);  
java.sql.Blob blob = rs.getBlob(column);  
InputStream in = blob.getBinaryStream();  
BufferedImage image = ImageIO.read(in);

at JLabel, you should use BufferedImage.

在 JLabel,您应该使用 BufferedImage。

回答by André R.

you could try this ...

你可以试试这个...

    // Fetch BLOB from DB
    Blob blb = stmt.executeQuery(...).getBlob("blobColumn");  

    // Read BLOB into byte-Array
    byte[] imagebytes = blb.getBytes(0, blb.length());

    // convert byte-Array into Buffered Image (Subclass of Image)
    BufferedImage theImage=ImageIO.read(new ByteArrayInputStream(imagebytes));

handle Exceptions and close streams in real code !

在实际代码中处理异常并关闭流!