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);
}