繁体   English   中英

ImageIO.read() 返回 null 值

[英]ImageIO.read() returning a null value

我正在尝试将字节数组转换为bufferedImage以显示在jLabel中,但ImageIO.read()属性返回 null 值,因此返回NullPonterException 我应该怎么办?

 InputStream input = new ByteArrayInputStream(array);
    try {
     BufferedImage bufer = ImageIO.read(input);
     ImageIcon icon=new ImageIcon(new ImageIcon(bufer).getImage().getScaledInstance(jLabel3.getWidth(), jLabel3.getHeight(), Image.SCALE_SMOOTH));
       
        jLabel3.setIcon(icon);
    } catch (IOException ex) {
        Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
    }`

根据javadocread(InputStream)方法...

“返回BufferedImage作为解码提供的InputStream的结果,其中ImageReader从当前注册的那些中自动选择InputStream包装在ImageInputStream中。如果没有注册的ImageReader声称能够读取生成的 stream,则返回null

最后一句话很可能解释了您的问题。


我应该怎么办?

所以你解决这个问题的方法是:

  1. 检查array的内容是否符合您的预期。
  2. 确定它是哪种图像格式,以及它是否正确表示。 例如,如果图像存储在数据库中或通过网络请求发送,请确保它没有在此过程中被破坏。
  3. 检查它是否是受支持的图像格式; 应该有一个注册的ImageReader class 。

感谢您帮助我解决问题,我将在此处发布回复以帮助其他人。

1.对数据库(postgresql)的查询必须是preparedStatement,因为如果您保存转换为byte []的图像,则此声明为您提供setBinaryStream功能,当您检索它并将其添加到byte []中时,没有任何变化

   ////This way save the image and his path (the last is optional)
    JFileChooser f = new JFileChooser();
    f.showOpenDialog(null);
    File file = f.getSelectedFile();
    FileInputStream s = null;
    String path = file.getAbsolutePath();
 try {
    s = new FileInputStream(file);
            Conexion();
            PreparedStatement pq = conexion.prepareStatement("INSERT INTO prueba(foto, cam) VALUES (?, ?);");
            pq.setBinaryStream(1, s, (int) file.length());
            pq.setString(2, path);
            pq.executeUpdate();
            s.close();
      } catch (ClassNotFoundException ex) {
            Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
        }



   /////This way retrive the info
   byte[] array = null;
   String photopath = "";
   try {
        Conexion();
        PreparedStatement p = conexion.prepareStatement("SELECT foto, cam FROM prueba;");
        ResultSet sq = p.executeQuery();
        while (sq.next()) {
            array = sq.getBytes("foto");
            photopath = sq.getString("cam");
            //jLabel3.setIcon(new ImageIcon(array));

            break;
        }
        sq.close();
        p.close();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(Add.class.getName()).log(Level.SEVERE, null, ex);
    }

    ImageIcon icon=new ImageIcon(array);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM