How to Read Image from MySQL Database in Java

In the previous tutorial, we have looked into How to Insert Image in MySQL Database Using Java. In this tutorial, we will learn how to read an image from a MySQL database table using Java (JDBC).
Checkout complete JDBC tutorial at Java Database Connectivity Tutorial.
You can download source code from my GitHub repository(the link given at end of this tutorial).

Retrieve Image from MySQL Database Table using Java

In the previous example, we have inserted an image into the database table. Now we are going to read the image back from the table:
package net.javaguides.jdbc;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Retrieve Image from MySQL Database Table using Java
 * @author Ramesh Fadatare
 *
 */
public class JdbcReadImage {

    public static void main(String[] args) {

        String url = "jdbc:mysql://localhost:3306/demo?useSSL=false";
        String user = "root";
        String password = "root";

        String query = "SELECT Data FROM Images LIMIT 1";

        try (Connection con = DriverManager.getConnection(url, user, password);     
             PreparedStatement pst = con.prepareStatement(query); 
             ResultSet result = pst.executeQuery()) {

            if (result.next()) {

                String fileName = "image.png";

                try (FileOutputStream fos = new FileOutputStream(fileName)) {

                    Blob blob = result.getBlob("Data");
                    int len = (int) blob.length();

                    byte[] buf = blob.getBytes(1, len);

                    fos.write(buf, 0, len);

                } catch (IOException ex) {

                    Logger lgr = Logger.getLogger(JdbcReadImage.class.getName());
                    lgr.log(Level.SEVERE, ex.getMessage(), ex);
                }
            }
        } catch (SQLException ex) {

            Logger lgr = Logger.getLogger(JdbcReadImage.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
}

Key points

  1. From JDBC 4.0, we don't need to include 'Class.forName()' in our code to load JDBC driver. JDBC 4.0 drivers that are found in your classpath are automatically loaded.
  2. We have used try-with-resources statements to automatically close JDBC resources.
Let's understand the above source code.

We select one record from the table:
String query = "SELECT Data FROM Images LIMIT 1";
The FileOutputStream object is created to write to a file. It is meant for writing streams of raw bytes such as image data:
String fileName = "image.png";

try (FileOutputStream fos = new FileOutputStream(fileName)) {
...
}
We get the image data from the Data column by calling the getBlob() method:
Blob blob = result.getBlob("Data");
We figure out the length of the blob data. In other words, we get the number of bytes:
int len = (int) blob.length();
The getBytes() method retrieves all bytes of the Blob object, as an array of bytes:
byte[] buf = blob.getBytes(1, len);
Checkout complete JDBC tutorial at Java Database Connectivity Tutorial.
The source code examples available on my GitHub Repository.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments