Save and Retrieve Image from MySql Database Using Java

Here you will get an example for save and retrieve image from MySql database using Java.

In development we generally use folders for managing images. But we can store images directly in database using BLOB (Binary Large Object) data type.

MySql has following blob types:

TINYBLOB: 255 bytes

BLOB: 64 KB

MEDIUMBLOB: 16 MB

LONGBLOB: 4 GB

Save and Retrieve Image from MySql Database Using Java

Depending upon requirement we can use any type. It is recommend no to use database for storing images with large size because it will increase the database size.

Below I have given an example of how to store and retrieve images from database. The description for table that I used is given below.

Table Details

 

Save and Retrieve Image from MySql Database Using Java

How to Save Image in Database

 

Above example will take image from location E:\\image.png and save it into database table. Actually you can’t see the image directly in the table. You have to retrieve it from database and then save it to some location. Below example shows how you can do this.

 

How to Retrieve Image from Database

 

Above example will fetch image from database and save it at location E:\\image1.png.

Comment below if you facing difficulty to understand above code.

Happy Coding!! 🙂 🙂

8 thoughts on “Save and Retrieve Image from MySql Database Using Java

  1. Solai

    Hi Neeraj,

    I need how to download the image in database table and the image is stored in server location.
    i am using spring and hibernate framework.

    Reply
  2. Gator

    hello..
    what would i need to change to retrieve to a jlabel in swing form?
    this is driving me crazy…
    Thanks
    Gator

    Reply
    1. Admin Post author

      After getting the image in byte from database add following lines.

      Image img = Toolkit.getDefaultToolkit().createImage(image);
      ImageIcon icon = new ImageIcon(img);
      JLabel lPhoto = new JLabel();
      lPhoto.setIcon(icon);

      Here image is of byte type. I hope this will help.

      Reply
      1. darmawan

        I’ve tried the way you and I do not get the error. but I also don’t get the image from a database

        Reply
  3. anmol

    “pos” + “length” arguments can not be larger than the BLOB’s length.
    above is an SqlException coming when i tried to retrieve an image .

    Reply
    1. Admin Post author

      The maximum length of Blob type is 64kb, you are trying to retrieve an image which is greater than 64kb. Use bigger types like mediumblob or longblob.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *