2

I have a little programm which stores a picture/imagefile in a MySQL Table as BLOB. Later, I need to be able to show this image in a seperate JFrame (already got this).

public static void showImage(File imageFile) {
    JFrame f = new JFrame();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    ImageIcon image = new ImageIcon(imageFile.getAbsolutePath());
    JLabel lbl = new JLabel(image);
    f.getContentPane().add(lbl);
    f.setSize(image.getIconWidth(), image.getIconHeight());

    int x = (screenSize.width - f.getSize().width) / 2; 
    int y = (screenSize.height - f.getSize().height) / 2;

    f.setLocation(x, y);
    f.setVisible(true);
}

What I currently do is: I get the BLOB data out of MySQL and create a local (temporary) file and display this in the JFrame.

private void createFile() {
    File imageFile = File.createTempFile("tmp-", ".jpeg", new File("./temp/"));
    OutputStream out = null;
    out = new FileOutputStream(imageFile);
    Blob blob = new javax.sql.rowset.serial.SerialBlob((byte[]) grdGrid.getModel().getValueAt(row, grdGrid.getColumn("picture").getModelIndex()));
    byte[] buff = blob.getBytes(1, (int) blob.length());
    out.write(buff);
    out.close();
    showImage(imageFile);
}

Is there any way to do this without creating a local File on the disk? Something like:

private void someMethod() { //just symbolic
    Blob blob = MySQL.getBlob();
    ImageIcon = blob.toImage();
}

Thanks for any help

sobrino
  • 153
  • 12

2 Answers2

4

ImageIcon has constructor where you can pass your array of image bytes.

 public ImageIcon (byte[] imageData, String description)

So you can write something like this

ImageIcon ii=new ImageIcon(blob.getBytes(1, (int) blob.length()),"description");
StanislavL
  • 56,971
  • 9
  • 68
  • 98
2

As shown here, you can get an InputStream from the Blob and pass it to ImageIO.read().

Blob blob = resultSet.getBlob(index);
InputStream stream = blob.getBinaryStream(0, blob.length());
BufferedImage image = ImageIO.read(stream);
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045