Saturday, 23 August 2014

JDBC : Retrieve Image

🚀 Master Java database programming, JDBC BLOB handling, and MySQL!

🔔 Subscribe to Ram N Java on YouTube

Retrieving Binary Image Data (BLOB) from MySQL Using JDBC

In relational databases like MySQL, multimedia files like JPEG and PNG images are stored as binary data inside BLOB (Binary Large Object) or LONGBLOB columns.

When reading this binary information back into your Java application using JDBC, the ResultSet provides the getBlob() method. Once you obtain the java.sql.Blob instance, you can extract the raw byte array using blob.getBytes() and reconstruct the file on your local disk using a FileOutputStream.

Database Table Structure (city_image)

Consider the following database table schema used to store city images:

CREATE TABLE `city_image` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `city_name` VARCHAR(50) NOT NULL,
    `photo` LONGBLOB,
    PRIMARY KEY (`id`)
);

Complete Java Source Code Example

The following Java program demonstrates how to fetch the binary image record from MySQL and save it as an image file on your system:

package com.ram.jdbc;

import java.io.File;
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;

public class JDBCRetrieveImageDemo {

    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";
    static final String USER = "root";
    static final String PASS = "root";

    public static void main(String[] args) {
        JDBCRetrieveImageDemo demo = new JDBCRetrieveImageDemo();
        demo.retrieveImage();
    }

    public void retrieveImage() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        FileOutputStream fos = null;

        try {
            // Step 1: Register MySQL JDBC Driver
            Class.forName(JDBC_DRIVER);

            // Step 2: Establish database connection
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // Step 3: Prepare and execute SELECT query
            String sql = "SELECT id, city_name, photo FROM city_image";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();

            // Step 4: Extract BLOB and write to file
            while (rs.next()) {
                String cityName = rs.getString("city_name");
                Blob photoBlob = rs.getBlob("photo");

                // Convert BLOB to byte array
                byte[] imageBytes = photoBlob.getBytes(1, (int) photoBlob.length());

                // Save to local directory
                File outputFile = new File("D:/downloads/" + cityName + ".jpg");
                fos = new FileOutputStream(outputFile);
                fos.write(imageBytes);

                System.out.println("Image successfully exported to: " + outputFile.getAbsolutePath());
            }

        } catch (ClassNotFoundException | SQLException | IOException e) {
            e.printStackTrace();
        } finally {
            // Step 5: Clean up file stream and database resources safely
            try {
                if (fos != null) fos.close();
                if (rs != null) rs.close();
                if (pstmt != null) pstmt.close();
                if (conn != null) conn.close();
            } catch (SQLException | IOException se) {
                se.printStackTrace();
            }
        }
    }
}

Key Steps & Best Practices

  • Retrieve the BLOB: Call rs.getBlob("photo") to obtain the binary column handle as a java.sql.Blob reference.
  • Convert to Bytes: Use blob.getBytes(1, (int) blob.length()) to extract the full binary byte payload (note that JDBC index positions start at 1).
  • Persist to Disk: Use FileOutputStream.write(imageBytes) to write the image file back to the filesystem.
  • Resource Cleanup: Always ensure the file output stream, ResultSet, PreparedStatement, and Connection are closed in the finally block to prevent resource leaks.

Related Tutorials You Might Enjoy


Click here to watch in Youtube : https://www.youtube.com/watch?v=JgKiAx3n4ao

Click the below Image to Enlarge
JDBC : Retrieve Image
JDBC : Retrieve Image
JDBC : Retrieve Image
JDBC : Retrieve Image
JDBC : Retrieve Image
JDBC : Retrieve Image
JDBCRetriveImageDemo.java
import java.io.FileOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCRetriveImageDemo
{
    // JDBC driver name and database URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/world";

    // Database credentials
    static final String USERNAME = "root";
    static final String PASSWORD = "root";

    public static void main(String[] args)
    {
        JDBCRetriveImageDemo jdbcRetriveImageDemo = new JDBCRetriveImageDemo();
        jdbcRetriveImageDemo.retriveImage();
    }

    private void retriveImage()
    {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try
        {
            /*
             * Register the JDBC driver in DriverManager
             */

            Class.forName(JDBC_DRIVER);

            /*
             * Establish connection to the Database using DriverManager
             */

            connection = DriverManager
                    .getConnection(DB_URL, USERNAME, PASSWORD);

            String sql = "select * from CITY_IMAGE";

            /*
             * Execute the query
             */
            preparedStatement = connection.prepareStatement(sql);
            ResultSet rs = preparedStatement.executeQuery();

            while (rs.next())
            {
                String imageName = rs.getString(2);
                Blob imageBlob = rs.getBlob(3);
                FileOutputStream fileOutputStream = new FileOutputStream(
                        "D:/Downloads/" + imageName);

                fileOutputStream.write(imageBlob.getBytes(1,
                        (int) imageBlob.length()));
                
                System.out.println(imageName + " has been stored in D:/Downloads/" );
                
                fileOutputStream.close();
            }

            rs.close();

        }
        catch (SQLException se)
        {

            se.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            /*
             * finally block used to close resources
             */
            try
            {
                if (preparedStatement != null)
                {
                    preparedStatement.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
            try
            {
                if (connection != null)
                {
                    connection.close();
                }
            }
            catch (SQLException sqlException)
            {
                sqlException.printStackTrace();
            }
        }

    }
}

Output
New york.jpg has been stored in D:/Downloads/

Environment Used 

JDK version : 1.7.0_51
Mysql Server version : 5.6.19 

To Download JDBCRetrieveImageDemoApp Project Click the below link

https://sites.google.com/site/javaee4321/jdbc/JDBCRetrieve%20ImageDemoApp.zip?attredirects=0&d=1

See also:

  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment

    Tutorials