How to store an image in a Microsoft Access database and then read it from the database?

0

I am developing a project, which under the circumstances my only option is to use access, but I have encountered this problem. I do not know how to store an image and read it from an Access database. I have looked in forums that indicate that with the following code I could solve my problem but that I get the following error: "javax.imageio.IIOException: Not a JPEG file: starts with 0xac 0xed" If someone could help me, I would really appreciate it. Annex the code that performs the insertion of the image and the reading of it: This segment of code performs the storage of the image in a field of type "OLE".

public boolean guardarfoto(String foto) {
    boolean ok=false;
        FileInputStream fis = null;
        try {
            File file = new File(foto);
            fis = new FileInputStream(file);

            PreparedStatement pstm =  con.getConnection().prepareStatement("insert into " +
                    " tImagenes(foto) " + " values(?)");                
            pstm.setBinaryStream(1, fis,(int) file.length());
            pstm.execute();
            pstm.close();
            ok=true;
        } catch (FileNotFoundException ex) {
            System.out.println(ex);
        } catch (SQLException e) {
            System.out.println(e);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                System.out.println(ex);
            }
        }
    return ok;
}
//metodo  que dado un parametro "id" realiza una consulta y devuelve como resultado
// una imagen
public Image getfoto(String id){
try{
PreparedStatement pstm =  con.getConnection().prepareStatement("SELECT " +
        " Foto " +
        " FROM tImagenes " +
        " where id = ? ");
     pstm.setString(1, id);
     ResultSet res = pstm.executeQuery();
     int i = 0;
     while(res.next()){
        //se lee la cadena de bytes de la base de datos
        byte[] b = res.getBytes("Foto");
        // esta cadena de bytes sera convertida en una imagen
        data = ConvertirImagen(b);
        i++;
     }
     res.close();
      } catch (IOException ex) {
          System.out.println(ex);
    }catch(SQLException e){
     System.out.println(e);
}
return data;
}

//metodo que dada una cadena de bytes la convierte en una imagen con extension 
jpeg
private Image ConvertirImagen(byte[] bytes) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
Iterator readers = ImageIO.getImageReadersByFormatName("jpeg");
ImageReader reader = (ImageReader) readers.next();
Object source = bis;
ImageInputStream iis = ImageIO.createImageInputStream(source);
reader.setInput(iis, true);
ImageReadParam param = reader.getDefaultReadParam();
return reader.read(0, param);
}
    
asked by Isaac Perez 03.11.2018 в 00:17
source

1 answer

1

Well, I found the answer by myself, I started to investigate more and I found another method that worked for me, if someone else goes through the same thing here is what I did and in a simple way:

public Image getfoto(String id){

 ImageIcon icono=null;

  try{
      // Se realiza una consulta la base de datos, nos regresara una imagen segun el id que asignemos
     PreparedStatement pstm =  con.getConnection().prepareStatement("SELECT " +
        " Foto " +
        " FROM tImagenes " +
        " where id = ? ");
     pstm.setString(1, id);
     ResultSet res = pstm.executeQuery();

     // Extraemos el resultado, el resultado se extrae de forma hexadecimal por lo que hay que convertir a bytes
     while(res.next()){

         // Capturamos la imagen en una variable tipo blob que permite extraer los bytes a utilizar
        Blob blob = res.getBlob(1);
        if(blob!=null){
            // Se establece que se tomara un rango de bytes es decir desde el primero hasta el ultimo
            byte[] data = blob.getBytes(1, (int)blob.length());
            BufferedImage img = null;
            // Se hace la lectura de los bytes y se almacena en el BufferedImage posibilitando realizar la conversion a imagen
            img = ImageIO.read(new ByteArrayInputStream(data));
            // Por ultimo se guarda en una variable Icon listo para ser utilizada la imagen
            icono = new ImageIcon(img);

return icono.getImage();
        }

     }
     res.close();
      } catch (IOException ex) {
          System.out.println(ex);
    }catch(SQLException e){
     System.out.println(e);
}
return icono.getImage();
}
    
answered by 03.11.2018 / 03:11
source