2

i am trying to save and retrieve imageicon in mysql Blob and want to set as icon on jlabel. here is the code.... Saving the image in class method:

     boolean savepost(String text , byte[] imageInByte, String date)
    {
    try{
      // if you only need a few columns, specify them by name instead of using "*"
      String query = "insert into 
      `post_data`(post_picture,post_text,post_date) values('"+imageInByte+"','"+text+"','"+date+"')";

    // create the java statement
    PreparedStatement preparedStmt = conn.prepareStatement(query);

     // execute the query, and get a java resultset
     preparedStmt.execute();
     }
     catch(Exception e)
     {
         System.out.println(e);
         return false;
     }
     return true;
      }

Retrieving the blob :

       void getTotalPosts(String date) {
        {

       try{
         // if you only need a few columns, specify them by name instead of using "*"
         String query = "select * from `post_data` where post_date='"+date+"'";

        // create the java statement
        Statement st = conn.createStatement();

     // execute the query, and get a java resultset
      ResultSet rs = st.executeQuery(query);

      // iterate through the java resultset
       int i =0 ;
         while (rs.next())
        {
          dat[i] = rs.getString("post_date");
          text[i]=rs.getString("post_text");
          byte[] imageInByte= rs.getBytes("post_picture");



                //Resize The ImageIcon
                ImageIcon image = new ImageIcon(imageInByte);

                 im[i] = image.getImage();

              }
            if(dat[0] == null)
              {
              System.out.println("cant find ");
               }
             }
           catch(Exception e)
           {
              System.out.println(e);
            }
           }

         }

here is my method to getImage in the same class ,where i am executing database quires :

     Image[] getImage()
     {
     return im;
     }

in this method i am passing this image array to another view class.

     private void share2ActionPerformed(java.awt.event.ActionEvent evt)   
      {                                       

    Image[] im = hd.getImage();
    s.setPost(2, hd.text[1],im[1]);        
    s.setVisible(true);      // TODO add your handling code here:

        }


     this is my method where i am setting the imageicon to jlabel.

        void setPost(int id , String text, Image image)
      {
      try{
       this.id.setText(" "+id);
       this.text.setText(text);
       System.out.println(image);
       Image myImg = image.getScaledInstance(this.image.getWidth(), 
       this.image.getHeight(),Image.SCALE_SMOOTH);
                ImageIcon newImage = new ImageIcon(myImg);
                this.image.setIcon(newImage);
      }
       catch(Exception e)
      {
        System.out.println(e);
       }
     }

i can't see anything on imageicon.

4
  • You're completely missing the point of prepared statements. the goal is to pass parameters, in a safe way. docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
    – JB Nizet
    Jan 29, 2018 at 8:56
  • For example, example, example, example Jan 29, 2018 at 8:58
  • Blob blob = rs.getBlob("post_picture"); BufferedImage img = ImageIO.read(blob.getBinaryStream()); System.out.println("img = " + img); JOptionPane.showMessageDialog(null, new JScrollPane(new JLabel(new ImageIcon(img)))); it gives me null pointer exception .....i am stuck in it man !
    – Awais A.
    Jan 29, 2018 at 9:19
  • The code storing the image in the database is completely wrong. Learn how to properly use prepared statements.
    – JB Nizet
    Jan 29, 2018 at 12:24

1 Answer 1

0

lets say we have a tabel in database called myimage->id,image . the whole structure of inserting byte array into database and retrieving from it is shown in the code below:

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.imageio.ImageIO;
import javax.sql.rowset.serial.SerialBlob;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

class Main 
{

    private static Connection conn ;
    private static PreparedStatement stmt;
    private static JFrame j = new JFrame();
    public Main()
    {


    }

    public static void main(String[] args) 
    {

        //insertBlob();
        //retrieveBlob();
        j.setSize(400,400);
        j.setVisible(true);
        j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }//main method

    public static void connect()
    {
        try
        {
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","username","password");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }


    }


    public static void insertBlob()
    {
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(Main.j);
        if(result == JFileChooser.APPROVE_OPTION)
        {
            try
            {
                //connect to database
                connect();

                //get file as image
                File file = fileChooser.getSelectedFile();
                BufferedImage image = ImageIO.read(file);

                //convert image to byte[]
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                ImageIO.write(image , "jpg" , output);
                byte[] img = output.toByteArray();

                //prepared statement
                String sql = "insert into myimage(id,image) values(1,?)";
                PreparedStatement stmt = conn.prepareStatement(sql);
                Blob blob = new SerialBlob(img);
                stmt.setBlob(1, blob);
                stmt.execute();

                //show on label
                JLabel label = new JLabel();
                ImageIcon imageIcon = new ImageIcon(image);
                label.setIcon(imageIcon);
                label.setBounds(10, 10, 100, 100);
                j.add(label);
            }//try
            catch(Exception e)
            {
                e.printStackTrace();
            }//catch
        }//if

    }//insert blob method


    public static void retrieveBlob()
    {
        try
        {
            //connect to database
            connect();

            //retrieve blob by prepared statement
            String sql = "select image from myimage where id=1";
            PreparedStatement stmt = conn.prepareStatement(sql);

            //put the result into resultset
            ResultSet result = stmt.executeQuery();

            //move the cursor to the first of the resultset
            result.next();

            //get blob
            Blob blob = result.getBlob("image");

            //convert blob to byte[]
            InputStream input = blob.getBinaryStream();
            byte[] img = new byte[new Long(blob.length()).intValue()];
            input.read(img);

            //convert byte[] to image
            InputStream inputStream = new ByteArrayInputStream(img);
            BufferedImage image = ImageIO.read(inputStream);

            //show in label
            JLabel label = new JLabel();
            ImageIcon imageIcon = new ImageIcon(image);
            label.setIcon(imageIcon);
            label.setBounds(10, 10, 100, 100);
            j.add(label);

        }//try
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }//retrieveBlob method

}//class Main

don't forget to add mysqlconnector into your JARs. this code is by no means similar to your code but i hope the structure of manipulating database by byte array helps you with your code

1
  • thanks for your help , i got this i was just using wrong prepared statements
    – Awais A.
    Jan 30, 2018 at 7:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.