Example usage for javax.imageio ImageReader reset

List of usage examples for javax.imageio ImageReader reset

Introduction

In this page you can find the example usage for javax.imageio ImageReader reset.

Prototype

public void reset() 

Source Link

Document

Restores the ImageReader to its initial state.

Usage

From source file:lucee.runtime.img.Image.java

public IIOMetadata getMetaData(Struct parent) {
    InputStream is = null;/*from   w w w .  ja  v a2  s .c o  m*/
    javax.imageio.stream.ImageInputStreamImpl iis = null;
    try {

        if (source instanceof File) {
            iis = new FileImageInputStream((File) source);
        } else if (source == null)
            iis = new MemoryCacheImageInputStream(new ByteArrayInputStream(getImageBytes(format, true)));
        else
            iis = new MemoryCacheImageInputStream(is = source.getInputStream());

        Iterator<ImageReader> readers = ImageIO.getImageReaders(iis);
        if (readers.hasNext()) {
            // pick the first available ImageReader
            ImageReader reader = readers.next();
            IIOMetadata meta = null;
            synchronized (sync) {
                // attach source to the reader
                reader.setInput(iis, true);

                // read metadata of first image
                meta = reader.getImageMetadata(0);
                meta.setFromTree(FORMAT, meta.getAsTree(FORMAT));
                reader.reset();
            }
            // generating dump
            if (parent != null) {
                String[] formatNames = meta.getMetadataFormatNames();
                for (int i = 0; i < formatNames.length; i++) {
                    Node root = meta.getAsTree(formatNames[i]);
                    //print.out(XMLCaster.toString(root));
                    addMetaddata(parent, "metadata", root);
                }
            }
            return meta;
        }
    } catch (Throwable t) {
    } finally {
        ImageUtil.closeEL(iis);
        IOUtil.closeEL(is);
    }
    return null;
}

From source file:org.geotools.utils.imagemosaic.MosaicIndexBuilder.java

/**
 * Main thread for the mosaic index builder.
 *///  w  w  w.  j  a  va2s .c  o  m
public void run() {

    // /////////////////////////////////////////////////////////////////////
    //
    // CREATING INDEX FILE
    //
    // /////////////////////////////////////////////////////////////////////

    // /////////////////////////////////////////////////////////////////////
    //
    // Create a file handler that write log record to a file called
    // my.log
    //
    // /////////////////////////////////////////////////////////////////////
    FileHandler handler = null;
    try {
        boolean append = true;
        handler = new FileHandler(new StringBuffer(locationPath).append("/error.txt").toString(), append);
        handler.setLevel(Level.SEVERE);
        // Add to the desired logger
        LOGGER.addHandler(handler);

        // /////////////////////////////////////////////////////////////////////
        //
        // Create a set of file names that have to be skipped since these are
        // our metadata files
        //
        // /////////////////////////////////////////////////////////////////////
        final Set<String> skipFiles = new HashSet<String>(
                Arrays.asList(new String[] { indexName + ".shp", indexName + ".dbf", indexName + ".shx",
                        indexName + ".prj", "error.txt", "error.txt.lck", indexName + ".properties" }));

        // /////////////////////////////////////////////////////////////////////
        //
        // Creating temp vars
        //
        // /////////////////////////////////////////////////////////////////////
        ShapefileDataStore index = null;
        Transaction t = new DefaultTransaction();
        // declaring a preciosion model to adhere the java double type
        // precision
        PrecisionModel precMod = new PrecisionModel(PrecisionModel.FLOATING);
        GeometryFactory geomFactory = new GeometryFactory(precMod);
        try {
            index = new ShapefileDataStore(
                    new File(locationPath + File.separator + indexName + ".shp").toURI().toURL());
        } catch (MalformedURLException ex) {
            if (LOGGER.isLoggable(Level.SEVERE))
                LOGGER.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            fireException(ex);
            return;
        }

        final List<File> files = new ArrayList<File>();
        recurse(files, locationPath);

        // /////////////////////////////////////////////////////////////////////
        //
        // Cycling over the files that have filtered out
        //
        // /////////////////////////////////////////////////////////////////////
        numFiles = files.size();
        String validFileName = null;
        final Iterator<File> filesIt = files.iterator();
        FeatureWriter<SimpleFeatureType, SimpleFeature> fw = null;
        boolean doneSomething = false;
        for (int i = 0; i < numFiles; i++) {

            StringBuffer message;
            // //
            //
            // Check that this file is actually good to go
            //
            // //         
            final File fileBeingProcessed = ((File) filesIt.next());
            if (!fileBeingProcessed.exists() || !fileBeingProcessed.canRead() || !fileBeingProcessed.isFile()) {
                // send a message
                message = new StringBuffer("Skipped file ").append(files.get(i))
                        .append(" snce it seems invalid.");
                if (LOGGER.isLoggable(Level.INFO))
                    LOGGER.info(message.toString());
                fireEvent(message.toString(), ((i * 99.0) / numFiles));
                continue;
            }

            // //
            //
            // Anyone has asked us to stop?
            //
            // //
            if (getStopThread()) {
                message = new StringBuffer("Stopping requested at file  ").append(i).append(" of ")
                        .append(numFiles).append(" files");
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine(message.toString());
                }
                fireEvent(message.toString(), ((i * 100.0) / numFiles));
                return;
            } // replacing chars on input path
            try {
                validFileName = fileBeingProcessed.getCanonicalPath();
            } catch (IOException e1) {
                fireException(e1);
                return;
            }
            validFileName = validFileName.replace('\\', '/');
            validFileName = validFileName.substring(locationPath.length() + 1,
                    fileBeingProcessed.getAbsolutePath().length());
            if (skipFiles.contains(validFileName))
                continue;
            message = new StringBuffer("Now indexing file ").append(validFileName);

            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), ((i * 100.0) / numFiles));
            try {
                // ////////////////////////////////////////////////////////
                //
                //
                // STEP 1
                // Getting an ImageIO reader for this coverage.
                //
                //
                // ////////////////////////////////////////////////////////
                ImageInputStream inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                if (inStream == null) {
                    if (LOGGER.isLoggable(Level.SEVERE))
                        LOGGER.severe(fileBeingProcessed
                                + " has been skipped since we could not get a stream for it");
                    continue;
                }
                inStream.mark();
                final Iterator<ImageReader> it = ImageIO.getImageReaders(inStream);
                ImageReader r = null;
                if (it.hasNext()) {
                    r = (ImageReader) it.next();
                    r.setInput(inStream);
                } else {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    //               try {
                    //                  r.dispose();
                    //               } catch (Exception e) {
                    //                  // ignore exception
                    //               }

                    // send a message
                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(":No ImageIO readeres avalaible.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 2
                // Getting a coverage reader for this coverage.
                //
                // ////////////////////////////////////////////////////////
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(new StringBuffer("Getting a reader").toString());
                final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder
                        .findFormat(files.get(i));
                if (format == null || !format.accepts(files.get(i))) {
                    // release resources
                    try {
                        inStream.close();
                    } catch (Exception e) {
                        // ignore exception
                    }
                    try {
                        r.dispose();
                    } catch (Exception e) {
                        // ignore exception
                    }

                    message = new StringBuffer("Skipped file ").append(files.get(i))
                            .append(": File format is not supported.");
                    if (LOGGER.isLoggable(Level.INFO))
                        LOGGER.info(message.toString());
                    fireEvent(message.toString(), ((i * 99.0) / numFiles));
                    continue;
                }
                final AbstractGridCoverage2DReader reader = (AbstractGridCoverage2DReader) format
                        .getReader(files.get(i));
                envelope = (GeneralEnvelope) reader.getOriginalEnvelope();
                actualCRS = reader.getCrs();

                // /////////////////////////////////////////////////////////////////////
                //
                // STEP 3
                // Get the type specifier for this image and the check that the
                // image has the correct sample model and color model.
                // If this is the first cycle of the loop we initialize
                // eveything.
                //
                // /////////////////////////////////////////////////////////////////////
                final ImageTypeSpecifier its = ((ImageTypeSpecifier) r.getImageTypes(0).next());
                boolean skipFeature = false;
                if (globEnvelope == null) {
                    // /////////////////////////////////////////////////////////////////////
                    //
                    // at the first step we initialize everything that we will
                    // reuse afterwards starting with color models, sample
                    // models, crs, etc....
                    //
                    // /////////////////////////////////////////////////////////////////////
                    defaultCM = its.getColorModel();
                    if (defaultCM instanceof IndexColorModel) {
                        IndexColorModel icm = (IndexColorModel) defaultCM;
                        int numBands = defaultCM.getNumColorComponents();
                        defaultPalette = new byte[3][icm.getMapSize()];
                        icm.getReds(defaultPalette[0]);
                        icm.getGreens(defaultPalette[0]);
                        icm.getBlues(defaultPalette[0]);
                        if (numBands == 4)
                            icm.getAlphas(defaultPalette[0]);

                    }
                    defaultSM = its.getSampleModel();
                    defaultCRS = actualCRS;
                    globEnvelope = new GeneralEnvelope(envelope);

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // getting information about resolution
                    //
                    // /////////////////////////////////////////////////////////////////////

                    // //
                    //
                    // get the dimension of the hr image and build the model
                    // as well as
                    // computing the resolution
                    // //
                    // resetting reader and recreating stream, turnaround for a
                    // strange imageio bug
                    r.reset();
                    try {
                        inStream.reset();
                    } catch (IOException e) {
                        inStream = ImageIO.createImageInputStream(fileBeingProcessed);
                    }
                    //let's check if we got something now
                    if (inStream == null) {
                        //skip file
                        if (LOGGER.isLoggable(Level.WARNING))
                            LOGGER.warning("Skipping file " + fileBeingProcessed.toString());
                        continue;
                    }
                    r.setInput(inStream);
                    numberOfLevels = r.getNumImages(true);
                    resolutionLevels = new double[2][numberOfLevels];
                    double[] res = getResolution(envelope, new Rectangle(r.getWidth(0), r.getHeight(0)),
                            defaultCRS);
                    resolutionLevels[0][0] = res[0];
                    resolutionLevels[1][0] = res[1];

                    // resolutions levels
                    if (numberOfLevels > 1) {

                        for (int k = 0; k < numberOfLevels; k++) {
                            res = getResolution(envelope, new Rectangle(r.getWidth(k), r.getHeight(k)),
                                    defaultCRS);
                            resolutionLevels[0][k] = res[0];
                            resolutionLevels[1][k] = res[1];
                        }
                    }

                    // /////////////////////////////////////////////////////////////////////
                    //
                    // creating the schema
                    //
                    // /////////////////////////////////////////////////////////////////////
                    final SimpleFeatureTypeBuilder featureBuilder = new SimpleFeatureTypeBuilder();
                    featureBuilder.setName("Flag");
                    featureBuilder.setNamespaceURI("http://www.geo-solutions.it/");
                    featureBuilder.add("location", String.class);
                    featureBuilder.add("the_geom", Polygon.class, this.actualCRS);
                    featureBuilder.setDefaultGeometry("the_geom");
                    final SimpleFeatureType simpleFeatureType = featureBuilder.buildFeatureType();
                    // create the schema for the new shape file
                    index.createSchema(simpleFeatureType);

                    // get a feature writer
                    fw = index.getFeatureWriter(t);
                } else {
                    // ////////////////////////////////////////////////////////
                    // 
                    // comparing ColorModel
                    // comparing SampeModel
                    // comparing CRSs
                    // ////////////////////////////////////////////////////////
                    globEnvelope.add(envelope);
                    actualCM = its.getColorModel();
                    actualSM = its.getSampleModel();
                    skipFeature = (i > 0 ? !(CRS.equalsIgnoreMetadata(defaultCRS, actualCRS)) : false);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because CRSs do not match.").toString());
                    skipFeature = checkColorModels(defaultCM, defaultPalette, actualCM);
                    if (skipFeature)
                        LOGGER.warning(new StringBuffer("Skipping image ").append(files.get(i))
                                .append(" because color models do not match.").toString());
                    // defaultCM.getNumComponents()==actualCM.getNumComponents()&&
                    // defaultCM.getClass().equals(actualCM.getClass())
                    // && defaultSM.getNumBands() == actualSM
                    // .getNumBands()
                    // && defaultSM.getDataType() == actualSM
                    // .getDataType() &&
                    //
                    // if (skipFeature)
                    // LOGGER
                    // .warning(new StringBuffer("Skipping image ")
                    // .append(files.get(i))
                    // .append(
                    // " because cm or sm does not match.")
                    // .toString());
                    // res = getResolution(envelope, new
                    // Rectangle(r.getWidth(0),
                    // r.getHeight(0)), defaultCRS);
                    // if (Math.abs((resX - res[0]) / resX) > EPS
                    // || Math.abs(resY - res[1]) > EPS) {
                    // LOGGER.warning(new StringBuffer("Skipping image
                    // ").append(
                    // files.get(i)).append(
                    // " because resolutions does not match.")
                    // .toString());
                    // skipFeature = true;
                    // }
                }

                // ////////////////////////////////////////////////////////
                //
                // STEP 4
                //
                // create and store features
                //
                // ////////////////////////////////////////////////////////
                if (!skipFeature) {

                    final SimpleFeature feature = fw.next();
                    feature.setAttribute(1,
                            geomFactory.toGeometry(new ReferencedEnvelope((Envelope) envelope)));
                    feature.setAttribute(
                            0, absolute
                                    ? new StringBuilder(this.locationPath).append(File.separatorChar)
                                            .append(validFileName).toString()
                                    : validFileName);
                    fw.write();

                    message = new StringBuffer("Done with file ").append(files.get(i));
                    if (LOGGER.isLoggable(Level.FINE)) {
                        LOGGER.fine(message.toString());
                    }
                    message.append('\n');
                    fireEvent(message.toString(), (((i + 1) * 99.0) / numFiles));
                    doneSomething = true;
                } else
                    skipFeature = false;

                // ////////////////////////////////////////////////////////
                //
                // STEP 5
                //
                // release resources
                //
                // ////////////////////////////////////////////////////////
                try {
                    inStream.close();
                } catch (Exception e) {
                    // ignore exception
                }
                try {
                    r.dispose();
                } catch (Exception e) {
                    // ignore exception
                }
                // release resources
                reader.dispose();

            } catch (IOException e) {
                fireException(e);
                break;
            } catch (ArrayIndexOutOfBoundsException e) {
                fireException(e);
                break;
            }

        }
        try {
            if (fw != null)
                fw.close();
            t.commit();
            t.close();
            index.dispose();
        } catch (IOException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
        createPropertiesFiles(globEnvelope, doneSomething);
    } catch (SecurityException el) {
        fireException(el);
        return;
    } catch (IOException el) {
        fireException(el);
        return;
    } finally {
        try {
            if (handler != null)
                handler.close();
        } catch (Throwable e) {
            // ignore
        }

    }

}

From source file:org.geotools.utils.imageoverviews.OverviewsEmbedder.java

public void run() {
    // did we create a local private tile cache or not?
    boolean localTileCache = false;
    ///*w  ww. j  a  v a2  s .  com*/
    // creating the image to use for the successive
    // subsampling
    //
    TileCache baseTC = JAI.getDefaultInstance().getTileCache();

    if (baseTC == null) {
        localTileCache = true;
        final long tilecacheSize = super.getTileCacheSize();
        baseTC = JAI.createTileCache();
        baseTC.setMemoryCapacity(tilecacheSize);
        baseTC.setMemoryThreshold(0.75f);
    }

    //
    // CHECK INPUT DIRECTORIES/FILES
    //
    if (sourcePath == null) {
        fireEvent("Provided sourcePath is null", overallProgress);
        return;
    }
    // getting an image input stream to the file
    final File file = new File(sourcePath);
    final File[] files;
    int numFiles = 1;
    StringBuilder message;
    if (!file.canRead() || !file.exists()) {
        fireEvent("Provided file " + file.getAbsolutePath() + " cannot be read or does not exist", 100);
        return;
    }
    if (file.isDirectory()) {
        if (wildcardString == null) {
            fireEvent("Provided wildcardString is null", 100);
            return;
        }
        final FileFilter fileFilter = new WildcardFileFilter(wildcardString);
        files = file.listFiles(fileFilter);
        numFiles = files.length;
        if (numFiles <= 0) {
            message = new StringBuilder("No files to process!");
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), 100);

        }

    } else
        files = new File[] { file };

    if (files == null || files.length == 0) {
        fireEvent("Unable to find input files for the provided wildcard " + wildcardString + " and input path "
                + sourcePath, 100);
        return;
    }
    // setting step
    overallProgressStep = 100 * 1.0 / numFiles;

    //
    // ADDING OVERVIEWS TO ALL FOUND FILES
    //
    for (fileBeingProcessed = 0; fileBeingProcessed < numFiles; fileBeingProcessed++) {

        message = new StringBuilder("Managing file  ").append(fileBeingProcessed).append(" of ")
                .append(files[fileBeingProcessed]).append(" files");
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine(message.toString());
        }

        overallProgress = overallProgressStep * fileBeingProcessed;
        fireEvent(message.toString(), overallProgress);

        if (getStopThread()) {
            message = new StringBuilder("Stopping requested at file  ").append(fileBeingProcessed)
                    .append(" of ").append(numFiles).append(" files");
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), overallProgress);
            return;
        }

        ImageInputStream stream = null;
        ImageWriter writer = null;
        ImageOutputStream streamOut = null;
        RenderedOp currentImage = null;
        RenderedOp newImage = null;
        try {

            File localFile = files[fileBeingProcessed];

            //
            // get a stream
            //
            stream = ImageIO.createImageInputStream(localFile);
            if (stream == null) {

                message = new StringBuilder("Unable to create an input stream for file")
                        .append(files[fileBeingProcessed]);
                if (LOGGER.isLoggable(Level.SEVERE)) {
                    LOGGER.severe(message.toString());
                }
                fireEvent(message.toString(), overallProgress);
                break;
            }
            stream.mark();

            //
            // get a reader
            //
            final Iterator<ImageReader> it = ImageIO.getImageReaders(stream);
            if (!it.hasNext()) {
                message = new StringBuilder("Unable to find a reader for file")
                        .append(files[fileBeingProcessed]);
                if (LOGGER.isLoggable(Level.SEVERE)) {
                    LOGGER.severe(message.toString());
                }
                fireEvent(message.toString(), overallProgress);
                break;
            }
            final ImageReader reader = (ImageReader) it.next();
            stream.reset();
            stream.mark();
            // is it a geotiff reader or not?
            if (!reader.getFormatName().toLowerCase().startsWith("tif")) {
                if (LOGGER.isLoggable(Level.INFO)) {
                    LOGGER.info("Discarding input file " + files[fileBeingProcessed]
                            + " since it is not a proper tif file.");
                }
                continue;
            }

            //
            // set input
            //
            reader.setInput(stream);
            ImageLayout layout = null;
            // tiling the image if needed
            int actualTileW = reader.getTileWidth(0);
            int actualTileH = reader.getTileHeight(0);
            if (!reader.isImageTiled(0) || (reader.isImageTiled(0) && (actualTileH != tileH && tileH != -1)
                    || (actualTileW != tileW && tileW != -1))) {

                message = new StringBuilder("Retiling image  ").append(fileBeingProcessed);
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine(message.toString());
                }
                fireEvent(message.toString(), overallProgress);
                layout = Utils.createTiledLayout(tileW, tileH, 0, 0);
            }
            stream.reset();
            reader.reset();
            reader.dispose();

            //
            // output image stream
            //
            if (externalOverviews) {
                // create a sibling file
                localFile = new File(localFile.getParent(),
                        FilenameUtils.getBaseName(localFile.getAbsolutePath()) + ".tif.ovr");
            }
            streamOut = ImageIOExt.createImageOutputStream(null, localFile);
            if (streamOut == null) {
                message = new StringBuilder("Unable to acquire an ImageOutputStream for the file ")
                        .append(files[fileBeingProcessed].toString());
                if (LOGGER.isLoggable(Level.SEVERE)) {
                    LOGGER.severe(message.toString());
                }
                fireEvent(message.toString(), 100);
                break;
            }

            //
            // Preparing to write the set of images. First of all I write
            // the first image `
            //
            // getting a writer for this reader
            writer = TIFF_IMAGE_WRITER_SPI.createWriterInstance();
            writer.setOutput(streamOut);
            writer.addIIOWriteProgressListener(writeProgressListener);
            writer.addIIOWriteWarningListener(writeProgressListener);
            ImageWriteParam param = writer.getDefaultWriteParam();

            //
            // setting tiling on the first image using writing parameters
            //
            if (tileH != -1 & tileW != -1) {
                param.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
                param.setTiling(tileW, tileH, 0, 0);

            } else {
                param.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
                param.setTiling(actualTileW, actualTileH, 0, 0);
            }
            if (this.compressionScheme != null && !Double.isNaN(compressionRatio)) {
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionType(compressionScheme);
                param.setCompressionQuality((float) this.compressionRatio);
            }

            final RenderingHints newHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
            newHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, baseTC));

            // read base image
            ParameterBlock pbjRead = new ParameterBlock();
            pbjRead.add(stream);
            pbjRead.add(Integer.valueOf(0));
            pbjRead.add(Boolean.FALSE);
            pbjRead.add(Boolean.FALSE);
            pbjRead.add(Boolean.FALSE);
            pbjRead.add(null);
            pbjRead.add(null);
            pbjRead.add(null);
            pbjRead.add(null);
            currentImage = JAI.create("ImageRead", pbjRead, newHints);
            message = new StringBuilder("Read original image  ").append(fileBeingProcessed);
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), overallProgress);
            int i = 0;
            //
            // OVERVIEWS CYLE
            //
            for (overviewInProcess = 0; overviewInProcess < numSteps; overviewInProcess++) {

                message = new StringBuilder("Subsampling step ").append(overviewInProcess + 1)
                        .append(" of image  ").append(fileBeingProcessed);
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine(message.toString());
                }
                fireEvent(message.toString(), overallProgress);

                // paranoiac check
                if (currentImage.getWidth() / downsampleStep <= 0
                        || currentImage.getHeight() / downsampleStep <= 0)
                    break;

                // SCALE

                // subsampling the input image using the chosen algorithm
                final SubsampleAlgorithm algorithm = SubsampleAlgorithm.valueOf(scaleAlgorithm);
                switch (algorithm) {
                case Average:
                    newImage = Utils.scaleAverage(currentImage, baseTC, downsampleStep, borderExtender);
                    break;
                case Filtered:
                    newImage = Utils.filteredSubsample(currentImage, baseTC, downsampleStep, lowPassFilter);
                    break;
                case Bilinear:
                    newImage = Utils.subsample(currentImage, baseTC, new InterpolationBilinear(),
                            downsampleStep, borderExtender);
                    break;
                case Bicubic:
                    newImage = Utils.subsample(currentImage, baseTC, new InterpolationBicubic(2),
                            downsampleStep, borderExtender);
                    break;
                case Nearest:
                    newImage = Utils.subsample(currentImage, baseTC, new InterpolationNearest(), downsampleStep,
                            borderExtender);
                    break;
                default:
                    throw new IllegalArgumentException("Invalid scaling algorithm " + scaleAlgorithm);//cannot get here

                }

                //set relevant metadata
                IIOMetadata imageMetadata = null;
                if (writer instanceof TIFFImageWriter) {
                    imageMetadata = writer.getDefaultImageMetadata(new ImageTypeSpecifier(newImage), param);
                    if (imageMetadata != null)
                        ((TIFFImageMetadata) imageMetadata).addShortOrLongField(
                                BaselineTIFFTagSet.TAG_NEW_SUBFILE_TYPE,
                                BaselineTIFFTagSet.NEW_SUBFILE_TYPE_REDUCED_RESOLUTION);
                }
                // write out
                if (!externalOverviews || i > 0)
                    writer.writeInsert(-1, new IIOImage(newImage, null, imageMetadata), param);
                else
                    writer.write(null, new IIOImage(newImage, null, imageMetadata), param);
                message = new StringBuilder("Step ").append(overviewInProcess + 1).append(" of image  ")
                        .append(fileBeingProcessed).append(" done!");
                if (LOGGER.isLoggable(Level.FINE)) {
                    LOGGER.fine(message.toString());
                }
                fireEvent(message.toString(), overallProgress);

                // switching images
                currentImage.dispose(); //dispose old image
                currentImage = newImage;

                i++;

            }

            overallProgress = 100;
            // close message
            message = new StringBuilder("Done with  image  ").append(fileBeingProcessed);
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine(message.toString());
            }
            fireEvent(message.toString(), overallProgress);
        } catch (Throwable e) {
            fireException(e);
        } finally {
            // clean up

            // clean caches if they are local
            if (localTileCache && baseTC != null)
                try {
                    baseTC.flush();
                } catch (Exception e) {
                }

            //
            // free everything
            try {
                if (streamOut != null)
                    streamOut.close();
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }

            try {
                if (writer != null)
                    writer.dispose();
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }

            try {
                if (currentImage != null)
                    currentImage.dispose();
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }

            try {
                if (newImage != null)
                    newImage.dispose();
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }

            try {
                if (stream != null)
                    stream.close();

            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }
        }
    }

    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine("Done!!!");

}