Inserting Image in Database Using Java

This application inserts an image into a database (SQL Server 2008). That is quite a common task these days. We need to create an application capable of storing textual as well as binary data from the application to the database and also to get the data from the database into our front end. Well talking about this application it is made on core Java. My next example will be covering the image store in database using servlets or JSP.

In this application we will be using Swing and AWT packages for creating the front end and our database is SQL Server 2008. For this example we will be using an Employee Table with the following structure.

CREATE TABLE [dbo].[Employee](
[EmpID] [int] IDENTITY(1,1) NOT NULL,
[EName] [varchar](30) NOT NULL,
[EAddress] [varchar](40) NOT NULL,
[ESalary] [float] NULL,
[EPhoto] [varbinary](max) NULL
)

And our front end screen shot is like the following:

Inserting Image in Database using Java

On the click of the browse button we are allowing the user to select an image file by applying a filter on FileChooser. If the user does not upload an image file then we are uploading a default image for it that is stored in src/resources/blank-image.png .

The following is the source code for it.

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

*/package insertimagedb;

import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.filechooser.FileSystemView;
import java.io.*;
import java.net.URL;
import javax.swing.filechooser.FileNameExtensionFilter;

/**
 *
 * @author Vishal.Gilbile
 */
public class EmpApp extends JFrame implements ActionListener {

    JTextField txtName, txtAdd, txtSalary, txtPath;
    JLabel lblName, lblAdd, lblSalary, lblPath;
    JButton btnSave, btnBrowse;
    JFileChooser fileChooser;
    JPanel pobj, innerPanel;
    GridBagConstraints gc = new GridBagConstraints();

    public EmpApp() {

        lblName = new JLabel("Name:");
        lblAdd = new JLabel("Address:");
        lblSalary = new JLabel("Salary:");
        lblPath = new JLabel("Select Photo:");
        txtName = new JTextField(15);
        txtAdd = new JTextField(15);
        txtSalary = new JTextField(15);
        txtPath = new JTextField(15);
        txtPath.setText("No File Uploaded");

        btnSave = new JButton("Save");
        btnSave.addActionListener(this);
        btnBrowse = new JButton("Browse");
        btnBrowse.addActionListener(this);

        pobj = new JPanel();        pobj.setLayout(new GridBagLayout());

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridy = 0;
        gc.gridx = 0;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(lblName, gc);

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 1;
        gc.gridy = 0;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(txtName, gc);

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 0;
        gc.gridy = 1;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(lblAdd, gc);

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 1;

        gc.gridy = 1;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(txtAdd, gc);

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 0;
        gc.gridy = 2;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(lblSalary, gc);

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 1;
        gc.gridy = 2;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(txtSalary, gc);

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 0;
        gc.gridy = 3;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(lblPath, gc);

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 1;
        gc.gridy = 3;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(txtPath, gc);

        gc.fill = GridBagConstraints.HORIZONTAL;
        gc.gridx = 2;
        gc.gridy = 3;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(btnBrowse, gc);

        gc.fill = GridBagConstraints.REMAINDER;
        gc.gridx = 1;
        gc.gridy = 4;
        gc.weighty = gc.weightx = 0.5;
        pobj.add(btnSave, gc);

        getContentPane().add(pobj);
        setSize(360, 180);
        setVisible(true);
        setResizable(false);
        setLocation(new Point(320, 240));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    /**
     * This function is used for inserting image into Employee Table
     *
     * @param imagePath filePath or profile Photo that needs to be saved
     */
    private void SaveImage(String imagePath) {
        try {
            byte[] rawBytes = null;
            FileInputStream fis = null;

            if (imagePath.equals("No File Uploaded")) {
                ClassLoader cl = this.getClass().getClassLoader();
                URL resouces = cl.getResource("resources/blank-image.png");
                imagePath = resouces.getFile();
            }

            File fileObj = new File(imagePath);
            fis = new FileInputStream(fileObj);
            float salary = Float.parseFloat(txtSalary.getText());

            //loading the JdbcOdbc driver for Sql Operations
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            //create and specify the DSN as myCon. and since my sql is using windows
authentication that's why i'm not ing
            //username and word as the second and third parameter in the getConnectionMethod of DriverManager class
            Connection con = DriverManager.getConnection("jdbc:odbc:myCon", "", "");
            PreparedStatement st = con.prepareStatement("insert into Employee(EName,EAddress,ESalary,EPhoto) values(?,?,?,?)");
            st.setString(1, txtName.getText());
            st.setString(2, txtAdd.getText());
            st.setFloat(3, salary);
            //st.setBinaryStream(4, fis);
            int imageLength = Integer.parseInt(String.valueOf(fileObj.length()));
            rawBytes = new byte[imageLength];
            fis.read(rawBytes, 0, imageLength);
            //st.setBinaryStream(4, (InputStream) fis, imageLength);
            st.setBytes(4, rawBytes);
            int count = st.executeUpdate();
            if (count > 0) {
                JOptionPane.showMessageDialog(this, "Data Saved Successfully");
            } else {
                JOptionPane.showMessageDialog(this, "Error Saving Data");
            }
        } catch (HeadlessException | IOException | ClassNotFoundException | NumberFormatException | SQLException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }
 
    /**
     * ActionPerformed Event used for handling button Click Event
     *
     * @param e ActionEvent Object
     */
    @Override
    public void actionPerformed(ActionEvent e) {

        JButton btn = (JButton) e.getSource();

        if (btn.equals(btnBrowse)) {

            fileChooser = new JFileChooser("C:\\", FileSystemView.getFileSystemView());
            fileChooser.setFileFilter(new FileNameExtensionFilter("Image Files", "jpg", "png", "tif", "gif", "bmp"));
            int returnVal = fileChooser.showOpenDialog(pobj);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                String fileName = fileChooser.getSelectedFile().getName();
                String extension = fileName.substring(fileName.lastIndexOf("."));
                if (extension.equalsIgnoreCase(".jpg") || extension.equalsIgnoreCase(".png")
                        || extension.equalsIgnoreCase(".bmp") || extension.equalsIgnoreCase(".tif")
                        || extension.equalsIgnoreCase(".gif")) {
                    txtPath.setText(fileChooser.getSelectedFile().getPath());
                } else {
                    JOptionPane.showMessageDialog(this, "Kindly Select Image File Only",
"Error", JOptionPane.ERROR_MESSAGE);
                }
            } else {
                txtPath.setText("No File Uploaded");
            }
        }
 else if (btn.equals(btnSave)) {
            SaveImage(txtPath.getText());
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        EmpApp objEmp = new EmpApp();
    }
}

The following is the output:



In the preceding case since the user is selecting an image, that image will be stored inside SQL Server.

Now for the second case if the user doesn't select any image then the default image should be stored. The following is the output for it.





With Regards,

Vishal Gilbile 

Up Next
    Ebook Download
    View all
    Learn
    View all