I want to save my image in a database in SQL in a field called fotoEmpleado of type IMAGE
, until then everything is fine, because I am saved in BYTES
The problem is when reading it, I want to show it in a Label on my form, I understand that it is getting that array of BYTES and convert it to an image but it sends me an error java.lang.NullPointerException
and I do not know how to read it. I leave my classes and methods that I use (MVC):
Method that makes the query and receives as a parameter the idEmployed:
public static String getImagenEmpleado(int idEmpleado) {
String consulta = "SELECT fotoEmpleado FROM Empleado WHERE idEmpleado="+idEmpleado;
return consulta;
}
Method that makes the connection to the DB and executes the query and converts the BYTES to IMAGE
:
public Image obtenerImagen(int idEmpleado) throws Exception {
Image foto = null;
//Creamos un objeto de conexion:
ConexionSQL conexion = new ConexionSQL();
//Declaramos el ResultSet:
ResultSet rs = null;
Statement stmt = null;
//Establecemos la conexion con la BD:
ConexionSQL.conectar();
stmt = ConexionSQL.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery(CommandsEmpleado.getImagenEmpleado(idEmpleado));
//Iteramos sobre cada registro devuelto:
if (rs.next()) {//si no encuentra la imagen
Blob blob = rs.getBlob("fotoEmpleado");
foto = javax.imageio.ImageIO.read(blob.getBinaryStream());
}
//Cerramos el ResultSet:
rs.close();
stmt.close();
//Cerramos la conexion:
conexion.desconectar();
//Devolvemos la foto del Empleado
return foto;
}
and in the view I send the parameter idEmployed and I send the image to the label:
ImageIcon image = new ImageIcon(controladorEmpleado.obtenerImagen(idEmpleado));
if (image.getIconHeight() > 342 || image.getIconWidth() > 230) {
ImageIcon imageScalada = new ImageIcon(image.getImage().getScaledInstance(90, 100, 100));
lblFotoEmpleado.setIcon(imageScalada);
} else {
lblFotoEmpleado.setIcon(image);
}
;
} catch (Exception ex) {
Logger.getLogger(PanelEmpleados.class.getName()).log(Level.SEVERE, null, ex);
}
or does anyone know another way to save and display the image in SQL and Java?