检索图像byte []并保存到MySql

时间:2018-01-29 08:53:51

标签: java mysql image

我正在尝试在mysql Blob中保存和检索imageicon,并希望在jlabel上设置为图标。 这是代码.... 在类方法中保存图像:

     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;
      }

检索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);
            }
           }

         }

这是我在同一个类中使用getImage的方法,我正在执行数据库quires:

     Image[] getImage()
     {
     return im;
     }

在这个方法中我将这个图像数组传递给另一个视图类。

     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);
       }
     }

我在imageicon上看不到任何东西。

1 个答案:

答案 0 :(得分:0)

假设我们在数据库中有一个名为myimage-> id,image的表格。 将字节数组插入数据库并从中检索的整个结构如下所示:

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

不要忘记将mysqlconnector添加到您的JAR中。这段代码与您的代码完全不同,但我希望通过字节数组操作数据库的结构可以帮助您使用代码