0

I am trying to show a image from mysql in a jtextpane but doesn't work,the problem appears when I try to turn the inputstream into BufferedImage, could you help me?

private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 508, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    JTextPane textPane = new JTextPane();
    textPane.setEditable(false);
    textPane.setBounds(55, 40, 370, 192);
    frame.getContentPane().add(textPane);

    try{
        Statement a = (Statement) con.createStatement();
        ResultSet b = a.executeQuery("Select imagen from chat");
        InputStream i = null;
        ImageIcon ii = null;
        if (b.next()) {
            i = b.getBinaryStream("imagen");
            BufferedImage bi = ImageIO.read(i);
            ii = new ImageIcon(bi);
            textPane.insertIcon(ii);
        }
    } catch ( SQLException | IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
    } 

}

the console said...

java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at imagen.initialize(imagen.java:75)

I can't find the solution

ByeBye
  • 6,650
  • 5
  • 30
  • 63
  • I think you should carefully read the [Documentation of ImageIO.read](http://docs.oracle.com/javase/7/docs/api/javax/imageio/ImageIO.html#read(java.io.InputStream)) to see if and when it returns `null`. – RealSkeptic Jun 19 '17 at 13:01
  • looks like the column valued you read from DB is null, make sure that the column name is correct. – Jobin Jun 19 '17 at 13:01
  • @Jobin if that was true, the error would not be at the constructor of `ImageIcon` but rather before that. – RealSkeptic Jun 19 '17 at 13:02
  • try yo use the following code `Blob blob = resultSet.getBlob("ImageField");` `int blobLength = (int) blob.length(); ` `byte[] imageAsBytes = blob.getBytes(1, blobLength); ` `ImageIcon ii = new ImageIcon(imageAsBytes);` – Jobin Jun 19 '17 at 13:06

1 Answers1

0

If the element on line 75 of the imagen.java file is probably null, you get a NullPointerException error. Go to solutuon

Abdullah G
  • 147
  • 1
  • 1
  • 8