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 ?
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.
}