How to Retrieve And Display Image From Mysql Database in java Netbeans

How to Retrieve And Display Image From Mysql Database in java Netbeans

This tutorial guide to retrieve and display image from mysql database in java project (JFrame). The previous tutorial shows you how to insert an image using java code to the MySQL database. That link provides under this post.

How to retrieve and display image from mysql database

Do you need help to remotely set up my any project on your machine or customize any project with your requirement please contact

Step 01 Open New java project

Step 02 Create Database

Should create a database and a table to store the image. The image store field of the table should be LONG BLOB data type.

Step 03 creates a database connection with java project

Database Connection class

package image;
import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnect {   
     public static Connection connect()
     Connection con=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");                                con=DriverManager.getConnection("jdbc:mysql://localhost:3306/yourDatabaseNameHere?","DatabaseUserNameHere","DatabasePasswordHere");   
catch (Exception e) 
   return con;

Add “MySQL.jdbc.Driver” to the project library.

If you need more information to connect Netbeans with MySQL database please watch this video

Step 04 Add new JFrame to project

Add a label and button to JFrame to retrieve and display image from mysql database

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import java.awt.Image;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main extends javax.swing.JFrame {
   private ImageIcon format=null;
   String fname=null;
   int s=0;
   byte[] pimage=null;
   Connection conn=null;

    public Main() {

private void txtdisplayidKeyReleased(java.awt.event.KeyEvent evt) {
    //put this code inside the button click event
         try {
            String sql="SELECT `id`, `image` FROM `img` WHERE id='"+txtdisplayid.getText()+"'";          
           PreparedStatement pst=conn.prepareStatement(sql);
           ResultSet rs=pst.executeQuery();
               byte[] imagedata=rs.getBytes("image");
               format=new ImageIcon(imagedata);
               Image mm=format.getImage();
               Image img2=mm.getScaledInstance(lbldisplay.getWidth(),        lbldisplay.getHeight(), Image.SCALE_SMOOTH);
               ImageIcon image=new ImageIcon(img2);
        } catch (Exception e) {

The technologies used in this tutorial

  • Java: All codes have been written using the java programming language.
  • MySql: MySql has used as a database for this project.
  • Netbeans: This project has developed inside of the Netbeans IDE.

More java projects>>

Java Tutorials