2

I have a db with a table "Images" with a field "Img" which contains image (type BLOB).

I extract an image with a query sql like this :

select img from images where id = 1

In a java swing project how can I obtain the image result of this query ?

1 Answer 1

4

This should work

Blob blob = rs.getBlob("img");
int blobLength = (int) blob.length();  

byte[] bytes = blob.getBytes(1, blobLength);
blob.free();
BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

You have options with how you want to add it the the frame. You can add it an a JLabel or you can paint it on a JPanel. Just depends on your requirements and/or preferences.

  • To use JLabel

    ImageIcon icon = new ImageIcon(bytes); // you can read straight from byte array
    JLabel label = new JLabel(icon);
    frame.add(label);
    
  • To paint on JPanel

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, getWidth(), getHeight(), this); 
        // img is the BufferedImage in the first code.
    }
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.