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

This tutorial guide to 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.

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

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) 
    {
        System.out.println("inter.DBConnect.connect()");
    }
   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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
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() {
    initComponents();
    conn=DBConnect.connect();
} 

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();
           if(rs.next())
           {          
               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);
               lbldisplay.setIcon(image);
            } 
           else
           {
          
           }
        } catch (Exception e) {
           
        }       
        
    }

Don’t Forget Subscribe Us

Be the first to comment

Leave a Reply

Your email address will not be published.


*