Retrieve image from MySql

Heya!

I was trying to retrieve a .bmp image stored as a MediumBlob in my MySql database using Java. On retrieval, the image is stored in a directory.

The concept goes as follows:

  • First, you create a .bmp file in a directory in which you wish to store the image. (Say, image.bmp)
  • Create an object of FileOutputStream (As FileOutputStream is meant for writing streams of raw bytes such as image data, and you would want to write the content of MediumBlob in the file image.bmp)
  • Create a byte array. (to hold the content of MediumBlob)
  • Use InputStream to read the byte data.
  • Write into the FileOutputStream object you created in step 2.

The program looks simple and make things much clearer.

File image = new File(“path to directory/image.bmp”);
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[1];
InputStream is = actual_result.getBinaryStream(2);  //2 refers to the index of image stored in your table
while (is.read(buffer) > 0)

{
fos.write(buffer);
}
fos.close();

Cheers,

aishwarya 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s