1

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                   

}

Leet-Falcon
  • 2,107
  • 2
  • 15
  • 23
Edgar
  • 543
  • 10
  • 20
  • `Image -> ImageIcon -> Image -> BufferedImage`, `ImageIcon`'s constructor doesn't do anything to the image, per Oracle's documentation, I'd get rid of it. Take a look at the documentation for `javax.ImageIO` or take a look at the link in my comment below. – Jonny Henly Dec 03 '15 at 21:20
  • I don't understand, so their is no image ? – Edgar Dec 03 '15 at 21:28
  • ok i got rid of imageicon as i saw it was redundant is this what cause my issue? – Edgar Dec 03 '15 at 21:36
  • What format is the image in? `LONGBLOB` or `jpg/gif/png`? – Jonny Henly Dec 03 '15 at 21:42
  • it was originally .png then we pushed it to the sql DB as LONGBLOB – Edgar Dec 03 '15 at 21:43
  • Look at [this tutorial](http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/), he takes a `byte[]` and creates a `BufferedImage`, he does it with a `jpg` just change to `png`, also he loads his `byte[]` from file, you already have yours from the DB. I don't think storing the image as `LONGBLOB` in the DB will change the byte structure, it should still be in `png` format. – Jonny Henly Dec 03 '15 at 21:46
  • It will depend on how the image was stored in the database – MadProgrammer Dec 03 '15 at 22:36
  • Something like [this](http://stackoverflow.com/questions/29983710/displaying-images-from-mysql-database-on-a-single-column-of-jtable/29983992#29983992) or [this](http://stackoverflow.com/questions/20752432/convert-bufferedinputstream-into-image/20753089#20753089) or [this](http://stackoverflow.com/questions/23621459/show-an-image-when-the-mouse-hovers-over-a-jtable-cell-using-the-preparerenderer/23621776#23621776) for example – MadProgrammer Dec 03 '15 at 22:38

1 Answers1

1

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));
Leet-Falcon
  • 2,107
  • 2
  • 15
  • 23