Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

jdbc - How to show an image from ms access to jpanel in java netbeans

The code I've used:

private void okActionPerformed(java.awt.event.ActionEvent evt)        
{                                   
    try {
        String Update = name.getText();

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection connection = DriverManager.getConnection("jdbc:odbc:NewPData");
        PreparedStatement psmnt = connection.prepareStatement("SELECT Image FROM Table1 where Name='" + Update + "'");
        ResultSet rs = psmnt.executeQuery();
        Blob blob = rs.getBlob("Image");
        int b;
        InputStream bis = rs.getBinaryStream("Image");

        FileOutputStream f = new FileOutputStream("Image.jpg");
        while ((b = bis.read()) >= 0) {
            f.write(b);
        }
        f.close();
        bis.close();

        icon = new ImageIcon(blob.getBytes(1L, (int) blob.length()));

        lblImage.setIcon(icon);

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

The exception showed:

       java.lang.UnsupportedOperationException

I have first stored the image in ms access and now I want to show it on a label. Please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This section of code doesn't make sense.

Blob blob = rs.getBlob("Image");
int b;
InputStream bis = rs.getBinaryStream("Image");

FileOutputStream f = new FileOutputStream("Image.jpg");
while ((b = bis.read()) >= 0) {
    f.write(b);
}
f.close();
bis.close();

icon = new ImageIcon(blob.getBytes(1L, (int) blob.length()));

You basically read the BLOB from result set to a file and then try and read it again to construct your image. It's possible that you've exhausted the stream.

Why not just read the image?

icon = new ImageIcon("Image.jpg");

Better yet, why not take advantage of the ImageIO API and read the stream directly, for-going the need to write out a temp file?

BufferedImage image = ImageIO.read(bis); 
icon = image == null ? null : new ImageIcon(image);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...