I am developing an application that manages a private medicine clinic. I have to save the data of the clients in a BD including their photograph, made with a webCam, I have managed to visualize the webCam, I have managed to make the photo, but the problem is when I add the photo to the BD. The insert does it perfectly, including that of the photo, but when I access the BD, I see that a file with the extension ".bin" has been inserted and when I download it, I can not open it with anything to verify that the photo corresponds to the the client's. Deputy current source, to see if someone can guide me a bit, even if I'm doing wrong the upload of the image.
Greetings and thanks in advance.
1 data insertion code.
public void insertarBd(){
PreparedStatement prepared;
String id = tfId.getText();
String nombre = tfNombre.getText();
String apellido1 = tfApellido1.getText();
String apellido2 = tfApellido2.getText();
String dni = tfDni.getText();
Date fechaNacimiento = Date.valueOf(tfFechaNacimiento.getText());
Date fechaAlta = Date.valueOf(LocalDate.now());
String poblacion = tfPoblacion.getText();
String direccion = taDireccion.getText();
int codigoPostal = Integer.parseInt(tfCodigoPostal.getText());
String provincia = tfProvincia.getText();
int telefonoFijo = 0;
int telefonoResponsable = 0;
int telefonoMovil = 0;
try{
telefonoFijo = Integer.valueOf(tfTelefonoFijo.getText());
telefonoResponsable = Integer.valueOf(tfTelefonoMovil.getText());
telefonoMovil = Integer.valueOf(tfTelefonoMovil.getText());
}catch(NumberFormatException e){
tfTelefonoFijo.setBackground(Color.red);
JOptionPane.showMessageDialog(null, "Solo numeros, por favor");
}
String nombreTutor = tfNombreTutor.getText();
Date fechaUltimaConsulta = Date.valueOf(LocalDate.now());
String consulta = tfConsulta.getText();
tfNombreTutor.setText(tfNombre.getText());
try {
blob = conexion.createBlob();
ObjectOutputStream oos = new ObjectOutputStream(blob.setBinaryStream(1));
oos.writeObject(imagen);
oos.close();
prepared = mysql.getConexion().prepareStatement("INSERT INTO pacientes (id, nombre, apellido1, apellido2, dni, fechaNacimiento, "
+ "fechaAlta, poblacion, direccion, codigoPostal, provincia, telefonoFijo, telefonoMovil, nombreTutor, "
+ "telefonoResponsable, fechaUltimaConsulta, consulta, foto)"
+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
// Parámetros para el preparedStatement
prepared.setString(1,id);
prepared.setString(2,nombre);
prepared.setString(3,apellido1);
prepared.setString(4,apellido2);
prepared.setString(5, dni);
prepared.setDate(6, fechaNacimiento);
prepared.setDate(7,fechaAlta);
prepared.setString(8, poblacion);
prepared.setString(9, direccion);
prepared.setInt(10, codigoPostal);
prepared.setString(11, provincia);
prepared.setInt(12, telefonoFijo);
prepared.setInt(13, telefonoMovil);
prepared.setString(14, nombreTutor);
prepared.setInt(15, telefonoResponsable);
prepared.setDate(16, fechaUltimaConsulta);
prepared.setString(17, consulta);
prepared.setBlob(18, blob);
// llamada al métdo ejecuta update el cual actualiza
//prepared.executeUpdate();
if(prepared.executeUpdate() >= 1){
JOptionPane.showMessageDialog(null, "Paciente insertado Correctamente");
}
prepared.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(null, "Problema con base de datos");
}catch(NumberFormatException e){
tfCodigoPostal.setBackground(Color.red);
tfTelefonoMovil.setBackground(Color.red);
}catch (IOException ex) {
Logger.getLogger(VentanaFormulario.class.getName()).log(Level.SEVERE, null, ex);
}
}
2nd code of the button with which I make the photo of the web cam
private void btCapturarActionPerformed(java.awt.event.ActionEvent evt) {
BufferedImage image = webcam.getImage();
imagen = new File(tfNombre.getText()+tfApellido1.getText()+".png");
try {
ImageIO.write(image, "PNG", imagen);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error al Guardar la foto");
}
}
As you can see, I use the blob data type to add the image, and the result in the BD is the the file inserted correctly
but when downloading it is a .bin file and I can not open it
Update I add ActionPerformed code to the save button, which calls the method insertsBD ()
public void insertarBd(){
PreparedStatement prepared;
String id = tfId.getText();
String nombre = tfNombre.getText();
String apellido1 = tfApellido1.getText();
String apellido2 = tfApellido2.getText();
String dni = tfDni.getText();
Date fechaNacimiento = Date.valueOf(tfFechaNacimiento.getText());
Date fechaAlta = Date.valueOf(LocalDate.now());
String poblacion = tfPoblacion.getText();
String direccion = taDireccion.getText();
int codigoPostal = Integer.parseInt(tfCodigoPostal.getText());
String provincia = tfProvincia.getText();
int telefonoFijo = 0;
int telefonoResponsable = 0;
int telefonoMovil = 0;
try{
telefonoFijo = Integer.valueOf(tfTelefonoFijo.getText());
telefonoResponsable = Integer.valueOf(tfTelefonoMovil.getText());
telefonoMovil = Integer.valueOf(tfTelefonoMovil.getText());
}catch(NumberFormatException e){
tfTelefonoFijo.setBackground(Color.red);
JOptionPane.showMessageDialog(null, "Solo numeros, por favor");
}
String nombreTutor = tfNombreTutor.getText();
Date fechaUltimaConsulta = Date.valueOf(LocalDate.now());
String consulta = tfConsulta.getText();
tfNombreTutor.setText(tfNombre.getText());
try {
/*bloque para imagen*/
blob = conexion.createBlob();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(blob.setBinaryStream(1));
oos.writeObject(imagen);
oos.close();
} catch (IOException ex) {
Logger.getLogger(VentanaFormulario.class.getName()).log(Level.SEVERE, null, ex);
}
prepared = mysql.getConexion().prepareStatement("INSERT INTO pacientes (id, nombre, apellido1, apellido2, dni, fechaNacimiento, "
+ "fechaAlta, poblacion, direccion, codigoPostal, provincia, telefonoFijo, telefonoMovil, nombreTutor, "
+ "telefonoResponsable, fechaUltimaConsulta, consulta, foto)"
+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
// Parámetros para el preparedStatement
prepared.setString(1,id);
prepared.setString(2,nombre);
prepared.setString(3,apellido1);
prepared.setString(4,apellido2);
prepared.setString(5, dni);
prepared.setDate(6, fechaNacimiento);
prepared.setDate(7,fechaAlta);
prepared.setString(8, poblacion);
prepared.setString(9, direccion);
prepared.setInt(10, codigoPostal);
prepared.setString(11, provincia);
prepared.setInt(12, telefonoFijo);
prepared.setInt(13, telefonoMovil);
prepared.setString(14, nombreTutor);
prepared.setInt(15, telefonoResponsable);
prepared.setDate(16, fechaUltimaConsulta);
prepared.setString(17, consulta);
prepared.setBlob(18, blob);
// llamada al métdo ejecuta update el cual actualiza
prepared.executeUpdate();
if(prepared.executeUpdate() >= 1){
JOptionPane.showMessageDialog(null, "Paciente insertado Correctamente");
}
prepared.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(null, "Problema con base de datos");
}catch(NumberFormatException e){
tfCodigoPostal.setBackground(Color.red);
tfTelefonoMovil.setBackground(Color.red);
}
}
Update 2 I have changed the method of uploading photo, and they no longer give null pointers or skip exceptions, but the image is not loaded from the BD
public void cargarFotoPaciente(){
String consulta = "SELECT foto FROM pacientes WHERE id=" + "'+tfId.getText()'";
ResultSet resultSet = mysql.ejecutaConsulta(consulta);
try {
while (resultSet.next()) {
byte[] imgBytes = resultSet.getBytes("foto");
if (imgBytes != null) {
ImageIcon imagenIcon = new ImageIcon(imgBytes);
jlFoto.setIcon(imagenIcon);
} else {
System.out.println("El paciente tiene foto pero no se puede cargar");
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error al cargar la foto desde la base de datos");
}
}
SOLUTION
Code to start the webcam
webcam = Webcam.getDefault();
webcam.setViewSize(WebcamResolution.VGA.getSize());
WebcamPanel panel = new WebcamPanel(webcam);
panel = new WebcamPanel(webcam);
panel.setFPSDisplayed(false);
panel.setDisplayDebugInfo(false);
panel.setImageSizeDisplayed(false);
panel.setMirrored(true);
panel.setSize(webcam.getViewSize());
jpDatosPaciente.add(panel);
pack();
panel.setBounds(768, 50, 220, 190);
panel.setVisible(true);
Button code to capture the webcam image
image = webcam.getImage();
archivo = new File(tfNombre.getText()+tfApellido1.getText() + ".png");
try {
ImageIO.write(image, "png", archivo);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Error al Guardar la foto");
}
Code of the insertion in the BD
PreparedStatement prepared;
String id = tfId.getText();
String nombre = tfNombre.getText();
String apellido1 = tfApellido1.getText();
String apellido2 = tfApellido2.getText();
String dni = tfDni.getText();
Date fechaNacimiento = Date.valueOf(tfFechaNacimiento.getText());
Date fechaAlta = Date.valueOf(LocalDate.now());
String poblacion = tfPoblacion.getText();
String direccion = taDireccion.getText();
int codigoPostal = Integer.parseInt(tfCodigoPostal.getText());
String provincia = tfProvincia.getText();
int telefonoFijo = 0;
int telefonoResponsable = 0;
int telefonoMovil = 0;
FileInputStream fis = null;
try{
telefonoFijo = Integer.valueOf(tfTelefonoFijo.getText());
telefonoResponsable = Integer.valueOf(tfTelefonoMovil.getText());
telefonoMovil = Integer.valueOf(tfTelefonoMovil.getText());
}catch(NumberFormatException e){
tfTelefonoFijo.setBackground(Color.red);
JOptionPane.showMessageDialog(null, "Solo numeros, por favor");
}
String nombreTutor = tfNombreTutor.getText();
Date fechaUltimaConsulta = Date.valueOf(LocalDate.now());
String consulta = tfConsulta.getText();
tfNombreTutor.setText(tfNombre.getText());
try {
/*bloque para imagen*/
//File archivo = new File(image + tfNombre.getText() + tfApellido1.getText());
fis = new FileInputStream(archivo);
prepared = mysql.getConexion().prepareStatement("INSERT INTO pacientes (id, nombre, apellido1, apellido2, dni, fechaNacimiento, "
+ "fechaAlta, poblacion, direccion, codigoPostal, provincia, telefonoFijo, telefonoMovil, nombreTutor, "
+ "telefonoResponsable, fechaUltimaConsulta, consulta, foto)"
+ " VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
// Parámetros para el preparedStatement
prepared.setString(1,id);
prepared.setString(2,nombre);
prepared.setString(3,apellido1);
prepared.setString(4,apellido2);
prepared.setString(5, dni);
prepared.setDate(6, fechaNacimiento);
prepared.setDate(7,fechaAlta);
prepared.setString(8, poblacion);
prepared.setString(9, direccion);
prepared.setInt(10, codigoPostal);
prepared.setString(11, provincia);
prepared.setInt(12, telefonoFijo);
prepared.setInt(13, telefonoMovil);
prepared.setString(14, nombreTutor);
prepared.setInt(15, telefonoResponsable);
prepared.setDate(16, fechaUltimaConsulta);
prepared.setString(17, consulta);
prepared.setBinaryStream(18, fis, (int)archivo.length());
// llamada al método ejecuta update el cual actualiza
if(prepared.executeUpdate() >= 1){
JOptionPane.showMessageDialog(null, "Paciente insertado Correctamente");
}
prepared.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(null, "Problema con base de datos");
}catch(NumberFormatException e){
tfCodigoPostal.setBackground(Color.red);
tfTelefonoMovil.setBackground(Color.red);
} catch (FileNotFoundException ex) {
Logger.getLogger(VentanaFormulario.class.getName()).log(Level.SEVERE, null, ex);
}
Code to show the image of the BD
String consulta = "SELECT foto FROM pacientes WHERE id=" + "'"+tfId.getText()+"'";
ResultSet resultSet = mysql.ejecutaConsulta(consulta);
Blob img = null;
Image img2 = null;
//ImageIcon icon = null;
try {
while (resultSet.next()) {
img = resultSet.getBlob("foto");
img2 = javax.imageio.ImageIO.read(img.getBinaryStream());
ImageIcon icon = new ImageIcon(img2);
ImageIcon icono = new ImageIcon(icon.getImage().getScaledInstance(jlFoto.getWidth(), jlFoto.getHeight(), Image.SCALE_DEFAULT));
jlFoto.setIcon(icono);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Error al cargar la foto desde la base de datos");
} catch (IOException ex) {
Logger.getLogger(VentanaFormulario.class.getName()).log(Level.SEVERE, null, ex);
}