Search code examples
javamysqlimageicon

how to make a LONGBLOB image from SQL into a buffered image for displaying in a label


I am trying display an array of bytes from a longblob image in a sql db and then make it into a BufferedImage and scale it to the size of my label, parts I know that work for sure is my SQL statement and the rescaling as I implemented it else where. I don't know if it is actually writing to the variable "image" or being made to icon then bufferedImage. im sure there is a way to make it a buffered image from the start but I am not too advanced with this part of java. any insight is helpful below is my code.

private void picPreviewerActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:

        String vinNumber = vinInput.getText();


try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/newbieswithauctions","root","root");
PreparedStatement ps = con.prepareStatement("SELECT itemImage FROM images WHERE itemVin='"+ vinNumber + "'");

ResultSet rs = ps.executeQuery();    
    byte[] image = null;
    while(rs.next()){
         image = rs.getBytes("itemImage");
    }
Image img = Toolkit.getDefaultToolkit().createImage(image);
ImageIcon icon = new ImageIcon(img);
Image pic = icon.getImage();
BufferedImage bufferedPic =(BufferedImage) pic;
try{

     BufferedImage scaled = getScaledInstance(
     bufferedPic, picView.getWidth(), picView.getHeight(), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
     picView.setIcon(new ImageIcon(scaled));
    }catch(Exception ex){

    }




}
catch(Exception ex)
{

}

}                                            

i have revised the code and i have this button and it will open a new form with the pic but nothing shows up this is the code in the button

  private void picPreviewerActionPerformed(java.awt.event.ActionEvent evt) {                                             
    // TODO add your handling code here:

    String vinNumber = vinInput.getText();


    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/newbieswithauctions","root","root");
        PreparedStatement ps = con.prepareStatement("SELECT itemImage FROM images WHERE itemVin='"+ vinNumber + "'");

        ResultSet rs = ps.executeQuery();    
            byte[] image = null;
            while(rs.next()){
                 image = rs.getBytes("itemImage");
            }
        InputStream in = new ByteArrayInputStream(image);
        bufferedPic = ImageIO.read(in);
        ImageIO.write(bufferedPic, "png", new File("C:\\Users\\geluna\\Desktop\\Software Engineering\\NWAGUI-sqlpicsworks\\NWAGUI-sqlpicsworks\\images\\newImage.png"));


    }
    catch(Exception ex)
    {

    }
    new PicSearchWin().setVisible(true);
}  

and in the form i have this in the main method so it populates the pic as soon as it opens but nothing happens but when i make a button in that form and put that code in there it will work when button is pressed. looks so bad. i want it to execute when form is opened. any ideas?

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

    // TODO add your handling code here:
    this.dispose();
}                                        

private void btnActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
       try{
     BufferedImage NewBufferedPic = ImageIO.read(new File("C:\\Users\\geluna\\Desktop\\Software Engineering\\NWAGUI-sqlpicsworks\\NWAGUI-sqlpicsworks\\images\\newImage.png"));
     BufferedImage scaled = getScaledInstance(
     NewBufferedPic, pic.getWidth(), pic.getHeight(), RenderingHints.VALUE_INTERPOLATION_BILINEAR, true);
     pic.setIcon(new ImageIcon(scaled));
    }catch(Exception ex){
         JOptionPane.showMessageDialog(null,"GAY", "Error ", JOptionPane.ERROR_MESSAGE);
    }
}                                   





/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(PicSearchWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(PicSearchWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(PicSearchWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(PicSearchWin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new PicSearchWin().setVisible(true);

        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton btn;
private javax.swing.JButton closeBtn;
public static javax.swing.JLabel pic;
// End of variables declaration                   

}


Solution

  • Why do you require BufferedImage?
    If you stored a BLOB then try this:

    Blob blob = rs.getBlob("itemImage"); 
    byte[] bytes = blob.getBytes(1, (int) blob.length());
    Image myImage = Toolkit.getDefaultToolkit().createImage(bytes);
    Image scaled = createYourScaledInstance();
    picView.setIcon(new ImageIcon(scaled));