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.

Awais A.
  • 39
  • 1
  • 7
  • You're completely missing the point of prepared statements. the goal is to pass parameters, in a safe way. https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html – JB Nizet Jan 29 '18 at 08:56
  • [For example](https://stackoverflow.com/questions/29983710/displaying-images-from-mysql-database-on-a-single-column-of-jtable/29983992#29983992), [example](https://stackoverflow.com/questions/20752432/convert-bufferedinputstream-into-image/20753089#20753089), [example](https://stackoverflow.com/questions/23621459/show-an-image-when-the-mouse-hovers-over-a-jtable-cell-using-the-preparerenderer/23621776#23621776), [example](https://stackoverflow.com/questions/35069359/trying-to-retrieve-both-text-and-blob-from-mysql-to-jtable/35072936#35072936) – MadProgrammer Jan 29 '18 at 08: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 '18 at 09:19
  • The code **storing** the image in the database is completely wrong. Learn how to properly use prepared statements. – JB Nizet Jan 29 '18 at 12:24

1 Answers1

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

parsa
  • 987
  • 2
  • 10
  • 23