2

I want to store image in binary format and retrieve it in binary format and display it in image format. I am able to store the file in binary format, but while retrieving it I get error java null pointer exception. Please point out the error. Here is the code:

import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class InsertImageTest {
int len;
    /**
     * This is used to get the Connection
     * 
     * @return
     */
    public Connection getConnection() {
        Connection connection = null;
        Statement stmt = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test", "root", "spanwave");
        } catch (Exception e) {
            System.out.println("Error Occured While Getting the Connection: - "
                    + e);
        }
        return connection;
    }

    /**
     * Insert Image
     */
     public Image getImageFile(String fileName) throws Exception {
InsertImageTest ins= new InsertImageTest();
Connection con=ins.getConnection();
Statement stmt=con.createStatement();
          //  String baseName=StoreImage.getBaseName(fileName);
            ResultSet rs=stmt.executeQuery("select * from trn_imgs where img_title='"+"Honda Car"+"'");
            if (!rs.next()) {
              System.out.println("Image:"+"honda car"+" not found");
              return null;
            }
           // int len=rs.getInt(2);

            byte [] b=new byte[len];
            InputStream in = rs.getBinaryStream(3);
            int n=in.read(b);
            System.out.println("n: "+n);
            in.close();
            Image img=Toolkit.getDefaultToolkit().createImage(b);
            System.out.println("Image: "+"honda car"+" retrieved ok, size: "+len);
            return img;
          }
    public void insertImage() throws IOException {
        Connection connection = null;
        PreparedStatement statement = null;
        FileInputStream inputStream = null;

        try {
            File image = new File("calender.png");
            inputStream = new FileInputStream(image);
            len=inputStream.available();
            connection = getConnection();
            statement = connection
                    .prepareStatement("insert into trn_imgs(img_title, img_data) "
                            + "values(?,?)");
            statement.setString(1, "Honda Car");
            statement.setBinaryStream(2, (InputStream) inputStream,
                    (int) (image.length()));

            statement.executeUpdate();
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException: - " + e);
        } catch (SQLException e) {
            System.out.println("SQLException: - " + e);
        } finally {
            try {
                connection.close();
                statement.close();
            } catch (SQLException e) {
                System.out.println("SQLException Finally: - " + e);
            }
        }

    }

    /***
     * Execute Program
     * 
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        InsertImageTest imageTest = new InsertImageTest();
        imageTest.insertImage();
    Image img=  imageTest.getImageFile("calender.png");
    }

}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Where do you get the NPE? What does the stack trace say? – creinig Mar 28 '13 at 09:03
  • 1
    You need to learn how to debug your code, identify which lines causes the null pointer exception – gerrytan Mar 28 '13 at 09:03
  • 1
    Addendum to the good comment by @gerrytan: [learn to read stack traces](http://stackoverflow.com/questions/12688068/how-to-read-and-understand-the-java-stack-trace). It's IMHO one of the core skills in java development. – creinig Mar 28 '13 at 09:13

2 Answers2

3

Unless something you are missing in your code:

 Statement stmt = null;
      //  String baseName=StoreImage.getBaseName(fileName);
        ResultSet rs=stmt.executeQuery("select * from trn_imgs where

 //stmt is null, right?
Eugene
  • 117,005
  • 15
  • 201
  • 306
2
connection = getConnection();
 Statement stmt = connection.createStatement();
 ResultSet rs=stmt.executeQuery("select * from trn_imgs where img_title='"+"Honda Car"+"'");
Alya'a Gamal
  • 5,624
  • 19
  • 34
  • i need one more help,now i am able to run but how to display the image.please tell me –  Mar 28 '13 at 09:29
  • http://stackoverflow.com/a/15599684/1743852: i wrote this answer before , so try it , i wish it can help you , and tell me if you faced any problem :) – Alya'a Gamal Mar 28 '13 at 09:39
  • see in my project i have to take the users datas including image and i have to display it in a jsp page.For example if user u1 resgiters once so when ever he logins with his userId and password then her details along with his photo should be displayed at the home page. i saw your answer and you are using swing. tell me how to get it in jsp page –  Mar 28 '13 at 09:43
  • i don't know how to use jsp , but when i search i found this code :`<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %> logo` , so you need the path of the image , so i suggest that you need to write the image , see this link :http://stackoverflow.com/a/15511055/1743852 – Alya'a Gamal Mar 28 '13 at 09:50
  • @javaL - You're welcome any time, if any thing goes wrong don't hesitate to ask me :) – Alya'a Gamal Mar 28 '13 at 09:54
  • do you know how to create a timepicker like we use datepicker. –  Mar 28 '13 at 10:44
  • @javaL - See [**this answer**](http://stackoverflow.com/questions/654342/is-there-any-good-and-free-date-and-time-picker-available-for-java-swing) it might be helpful. – Alya'a Gamal Mar 28 '13 at 10:46