Skip to main content

imagewriter disposed but still lock the output file

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
No replies
omarblumen
Offline
Joined: 2014-02-04

Dudes i got a problem... i am scanning TIFFs to a multipage tiff with a reference name. If i create the tiff with the imageoutputstream and its imagewriter i have no problem, but if i want to insert new images to the tiff created before, i have to first create an imageinputstream and its reader to read all the pages and create a new tiff and write the readed images and then insert the new ones, but when i flush the imageoutputstream, then dispose the writer and then close the imageoutputstream, the thread finish but it stills locks the output file.. i dont know very well java but i was reading any kind of papers to find a solution, like try with resources or try with finally but the problem remains.... could you please heeeeeelp!!!

here is the sample code:

private void escanea(){
splitPanelDigitalizar();
try {
status.setText("Trabajando..."); //PONER EL VALOR DEL CAMPO DE TEXTO status
TwainSource source = TwainManager.selectSource(MainPanel.this, null); //MOSTRAR VENTANA DE SELECCION DEL SCANNER TWAIN
//SI EL TWAIN SOURCE NO ES NULO ENTONCES
if (source != null) {
source.setGrayScaleMode(); //MODO ESCALA DE GRISES
source.setResolution(300); //DPIS
source.setCompression(0); //NINGUNA
source.setImageFileFormat(0); //0 .- TIFF // 6.- MULTIPAGE TIFF
source.setVisible(true); //VISIBILIDAD DE LA VENTANA DE PROPIEDADES TWAIN
source.setFeederEnabled(true); // ALIMENTACION HABILITADA
source.setAutoFeed(true); // ALIMENTACION AUTOMATICA
source.setTransferCount(-1); // MULTIPLES PAGINAS SIN LIMITE
//source.set

try{

//SELECCIONAMOS EL PARAMETRO PARA COMPRIMIR EL TIFF en PackBits
TIFFImageWriteParam writeParam = new TIFFImageWriteParam(Locale.ENGLISH);
writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
writeParam.setCompressionType("PackBits");
////////////

//CHECAR SI EXISTE EL ARCHIVO TIFF, SI ES ASI RENOMBRARLO Y ABRIRLO, LEERLO PARA CREAR EL NUEVO ORIGINAL
//PARA AGREGARLE LAS IMAGENES.
if(insertar){// || banTIFF){
//CREAR EL LECTOR DE ARCHIVOS
Iterator readers=ImageIO.getImageReadersByFormatName("tiff");
ImageReader reader= (ImageReader) readers.next();
//CREAR EL STREAM DE ENTRADA
try(ImageInputStream iis=ImageIO.createImageInputStream(new File(strTEMP))){
//ASIGNARLE EL STREAM DE ENTRADA AL LECTOR DE ARCHIVOS.
reader.setInput(iis);

//CREAR EL ARCHIVO TIFF PARA AGREGARLE LAS IMAGENES ESCANEADAS
Iterator writers = ImageIO.getImageWritersByFormatName("tiff");
ImageWriter writer = (ImageWriter) writers.next();

//CREAR EL STREAM DE SALIDA
try(ImageOutputStream ios = ImageIO.createImageOutputStream(new FileOutputStream(strTIFF))){

//ASIGNARSELO AL ESCRITOR DE ARCHIVOS
writer.setOutput(ios);

BufferedImage imageN;
int numImages = reader.getNumImages(true);
//REINICIAR LA LISTA
listModel = new DefaultListModel<>();
for (int i = 0; i < numImages; i++) {
imageN = reader.read(i, null);
Integer elementoX=listModel.getSize()+1;

if(i==0){
writer.write(null, new IIOImage(imageN, null, null), writeParam);
}
else if(i>0){
writer.writeInsert(-1, new IIOImage(imageN, null, null), writeParam);
}
listModel.addElement(elementoX);
}

// MIENTRAS SEA VERDAD
while (true) {
MorenaImage morenaImage = new MorenaImage(source);//CREAR LA IMAGEN DESDE EL ESCANNER TWAIN
int imageStatus = morenaImage.getStatus(); //TRAER EL ESTATUS DE LA IMAGEN
//SI EL ESTATUS DE LA IMAGEN ES UNA IMAGEN COMPLETA Y NO HAY MAS PIXELES QUE EMITIR
if (imageStatus == ImageConsumer.STATICIMAGEDONE) {
int imageWidth = morenaImage.getWidth();//ANCHO DE IMAGEN
int imageHeight = morenaImage.getHeight();//ALTO DE IMAGEN
int imagePixelSize = morenaImage.getPixelSize(); //TAMA├'O DE LA IMAGEN EN PIXELES
//GUARDAR LA IMAGEN ORIGINAL Y CREAR EL THUMBNAIL
Image imageJPG = Toolkit.getDefaultToolkit().createImage(morenaImage);
BufferedImage bufferedImage = new BufferedImage(imageJPG.getWidth(null), imageJPG.getHeight(null), BufferedImage.TYPE_INT_RGB);
bufferedImage.createGraphics().drawImage(imageJPG, 0, 0, null);
Integer elemento=listModel.getSize()+1;

/* ARCHIVOS JPG
String fileName="/scg/imgtmp/file"+elemento+".jpg";
File outputfile = new File(fileName);
ImageIO.write(bufferedImage, "jpg", outputfile);
*/

//TIFF
if(elemento==1){
writer.write(null, new IIOImage(bufferedImage, null, null), writeParam);
}
else if(elemento>1){
writer.writeInsert(-1, new IIOImage(bufferedImage, null, null), writeParam);
}
//////////////

listModel.addElement(elemento);

if (TwainSource.class.isInstance(source)) {
status.setText("Listo");
} else {
status.setText("Done - actual image size is " + imageWidth + " x " + imageHeight + " x " + imagePixelSize + " ...");
}
validate();
if (TwainSource.class.isInstance(source) && ((TwainSource) source).hasMoreImages()) {
continue;
}
} else if (imageStatus == ImageConsumer.IMAGEABORTED) {
status.setText("Cancelado, intente nuevamente...");
} else if (imageStatus == ImageConsumer.IMAGEERROR) {
status.setText("Fall├│, intente nuevamente...");
}
break;
}//END WHILE SCANNING IMAGES
}//TRY IOS
finally{
try{
writer.dispose();
}
catch(Throwable tr){
JOptionPane.showMessageDialog(MainPanel.this, "Writer: "+tr, "Info", JOptionPane.ERROR_MESSAGE);
}
}
}// TRY IIS
finally{
//ELIMINAMOS EL ARCHIVO TEMPORAL
try{
reader.dispose();
try{
Files.delete(tempPath);
}
catch(java.io.IOException iooE){
JOptionPane.showMessageDialog(MainPanel.this, "Error Eliminando: "+iooE, "Info", JOptionPane.ERROR_MESSAGE);
}
}
catch(java.awt.HeadlessException hde){
JOptionPane.showMessageDialog(MainPanel.this, "Reader: "+hde, "Info", JOptionPane.ERROR_MESSAGE);
}
}

} //IF FILE EXISTS
//SI NO EXISTE EL ARCHIVO TIFF CREARLO DESDE CERO.

}//END TRY WRITER
catch(SK.gnome.twain.TwainException|java.awt.HeadlessException|java.io.IOException eeX){
JOptionPane.showMessageDialog(MainPanel.this, eeX.toString(), "Info", JOptionPane.ERROR_MESSAGE);
}

if(listModel.getSize()>0){
imageList.setSelectedIndex(0);
imageList.requestFocusInWindow();
rotarIzqAction.setEnabled(true);
rotarDerAction.setEnabled(true);
rotar180Action.setEnabled(true);
eliminarAction.setEnabled(true);
if(idExpediente!=null) guardarAction.setEnabled(true);
eliminarTodoAction.setEnabled(true);
}
} else {
status.setText("Fall├│, intente nuevamente...");
}
}catch (NoSuchMethodError error) {
JOptionPane.showMessageDialog(MainPanel.this, error.toString()+" -> Previous version of Morena is installed in " + System.getProperty("java.home") + ".\nYou have to remove it first.\nClick OK to terminate browser.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}catch(SK.gnome.twain.TwainException|java.awt.HeadlessException exE){
JOptionPane.showMessageDialog(MainPanel.this, exE.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}finally {
try {
Morena.close();
} catch (SK.gnome.morena.MorenaException exception) {
JOptionPane.showMessageDialog(MainPanel.this, exception.toString(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
}´╗┐