Insert and Retrieve Images from MySql Table Using Java

Original Post: http://harmeetsingh13.blogspot.com/2013/03/insert-and-retrieve-images-from-mysql.html

Demonstrate to insert and retrieve the images from database table. Mostly the images are stored from outside the database( some folders) and store the path of the images into database tables . but in some scenario we need to insert the images into database tables in binary format.

Requirements :

  1. Download and Install JDK on your System.
  2. Download and Install MySql server and install.
  3. Download MySQL Connector or Drivers for use MySQL with Java.

Create Table in MySQL : 

CREATE TABLE `image` (
  `id` varchar(45) DEFAULT NULL,
  `size` int(11) DEFAULT NULL,
  `image` longblob
);
In MySQL when we use the blob type to store the data , it support only 5 kb image capacity. its depends on different database vendors . according to some more database vendors the blob type support large capacity. So the type of image type is depends on database vendors.

Insert The Image In Database : 

import java.sql.*;
import java.io.*;
public class InsertImagesMysql{
public static void main(String[] args){
System.out.println(“Insert Image Example!”);
String driverName = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost:3306/”;
String dbName = “test”;
String userName = “root”;
String password = “root”;
Connection con = null;
try{
  Class.forName(driverName);
  con = DriverManager.getConnection(url+dbName,userName,password);
  Statement st = con.createStatement();
  File imgfile = new File(“pic.jpg”);
 FileInputStream fin = new FileInputStream(imgfile);
  PreparedStatement pre =
  con.prepareStatement(“insert into Image values(?,?,?)”);
  pre.setString(1,”test”);
  pre.setInt(2,3);
  pre.setBinaryStream(3,(InputStream)fin,(int)imgfile.length());
  pre.executeUpdate();
  System.out.println(“Successfully inserted the file into the database!”);
  pre.close();
  con.close();
}catch (Exception e1){
System.out.println(e1.getMessage());
}
}
}

Compile & Run The Task :

  1.  javac -cp mysql-connector-java-5.0.5-bin.jar;. InsertImagesMysql.java
  2.   java -cp mysql-connector-java-5.0.5-bin.jar;. InsertImagesMysql

 

Retrieve The Image From Database :

import java.sql.*;
import java.io.*;
public class RetriveImagesMysql{
public static void main(String[] args){
System.out.println(“Retrive Image Example!”);
String driverName = “com.mysql.jdbc.Driver”;
String url = “jdbc:mysql://localhost:3306/”;
String dbName = “test”;
String userName = “root”;
String password = “root”;
Connection con = null;
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“select image from image”);
int i = 0;
while (rs.next()) {
InputStream in = rs.getBinaryStream(1);
OutputStream f = new FileOutputStream(new File(“test”+i+”.jpg”));
i++;
int c = 0;
while ((c = in.read()) > -1) {
f.write(c);
}
f.close();
in.close();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

Compile & Run The Task :

  1.  javac -cp mysql-connector-java-5.0.5-bin.jar;. RetriveImagesMysql.java
  2.   java -cp mysql-connector-java-5.0.5-bin.jar;. RetriveImagesMysql

Click Here To Download The Source Code

Display Image on JFrame from MySQL

Original Post: http://javaknowledge.info/display-image-on-jframe-from-mysql/

In my previous post I have shown you how to insert image with resizing to MySQL db. In this example I want to display the stored images on to JFrame.


The following method retrieves image from database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public void getImageById(int id) {
        String query = "select image from save_image where id = ?";
        try {
            PreparedStatement stmt = con.prepareStatement(query);
            stmt.setInt(1, id);
            ResultSet result = stmt.executeQuery();
            byte[] bytes = null;
            if (result.next()) {
                bytes = result.getBytes(1);
            }
            if (bytes != null) {
                image = toImage(bytes);
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

I want to display the image on to a JPanel, so I have created the class-

1
2
3
4
5
6
7
8
9
private class PicturePanel extends JPanel {
        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, null);
            this.revalidate();
            this.repaint();
        }
    }

In my JFrame I have created a JPanel like this-

1
2
JPanel pictuLabel;
pictuLabel = new PicturePanel();

Screenshot:
display_image_from_mysql

Show simple open file dialog using JFileChooser

Original Post: http://www.codejava.net/java-se/swing/show-simple-open-file-dialog-using-jfilechooser

The steps to create a simple open file dialog using JFileChooser class are as follows:

  1. Add required import statements:
    1
    2
    import javax.swing.JFileChooser;
    import java.io.File;       
  2. Create a new instance ofJFileChooser class:
    1
    JFileChooser fileChooser = new JFileChooser();
  3. Set current directory:
    1
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));

    The current directory is initial directory where the dialog looks for files. The above line sets the current directory to user’s home directory.

  4. Show up the dialog:
    1
    int result = fileChooser.showOpenDialog(parent);

    where parent is an instance of a Component such as JFrame, JDialog or JPanelwhich is parent of the dialog.

  5. Check if the user selects a file or not:
    If the user selects a file, the variable result will hold a value ofJFileChooser.APPROVE_OPTION. So it’s necessary to check return value of the methodshowOpenDialog():

    1
    2
    3
    if (result == JFileChooser.APPROVE_OPTION) {
        // user selects a file
    }
  6. Pick up the selected file:
    1
    File selectedFile = fileChooser.getSelectedFile();
  7. And the whole code snippet is as follows:
    1
    2
    3
    4
    5
    6
    7
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
    int result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        System.out.println("Selected file: " + selectedFile.getAbsolutePath());
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s