Example usage for javax.imageio ImageWriteParam MODE_EXPLICIT

List of usage examples for javax.imageio ImageWriteParam MODE_EXPLICIT

Introduction

In this page you can find the example usage for javax.imageio ImageWriteParam MODE_EXPLICIT.

Prototype

int MODE_EXPLICIT

To view the source code for javax.imageio ImageWriteParam MODE_EXPLICIT.

Click Source Link

Document

A constant value that may be passed into methods such as setTilingMode or setCompressionMode to enable a feature for future writes.

Usage

From source file:org.dcm4che.tool.dcm2jpg.Dcm2Jpg.java

public void initImageWriter(String formatName, String suffix, String clazz, String compressionType,
        Number quality) {/*from ww  w. j  av  a2  s .co  m*/
    Iterator<ImageWriter> imageWriters = ImageIO.getImageWritersByFormatName(formatName);
    if (!imageWriters.hasNext())
        throw new IllegalArgumentException(
                MessageFormat.format(rb.getString("formatNotSupported"), formatName));
    this.suffix = suffix != null ? suffix : formatName.toLowerCase();
    imageWriter = imageWriters.next();
    if (clazz != null)
        while (!clazz.equals(imageWriter.getClass().getName()))
            if (imageWriters.hasNext())
                imageWriter = imageWriters.next();
            else
                throw new IllegalArgumentException(
                        MessageFormat.format(rb.getString("noSuchImageWriter"), clazz, formatName));
    imageWriteParam = imageWriter.getDefaultWriteParam();
    if (compressionType != null || quality != null) {
        imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        if (compressionType != null)
            imageWriteParam.setCompressionType(compressionType);
        if (quality != null)
            imageWriteParam.setCompressionQuality(quality.floatValue());
    }
}

From source file:org.dcm4che2.tool.dcm2jpg.Dcm2Jpg.java

private void encodeByImageIO(BufferedImage bi, File dest) throws IOException {
    ImageWriter writer = getImageWriter(imageWriterClassname);
    ImageOutputStream out = null;
    try {//  w ww. j av  a 2 s .  c o m
        out = ImageIO.createImageOutputStream(dest);
        writer.setOutput(out);
        ImageWriteParam iwparam = writer.getDefaultWriteParam();
        if (iwparam.canWriteCompressed()) {
            iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            String[] compressionTypes = iwparam.getCompressionTypes();
            if (compressionTypes != null && compressionTypes.length > 0) {
                if (compressionType != null || iwparam.getCompressionType() == null) {
                    for (int i = 0; i < compressionTypes.length; i++) {
                        if (compressionType == null
                                || compressionTypes[i].compareToIgnoreCase(compressionType) == 0) {
                            iwparam.setCompressionType(compressionTypes[i]);
                            break;
                        }
                    }
                }
            }
            if (imageQuality != null)
                iwparam.setCompressionQuality(imageQuality);
        } else if (imageQuality != null) {
            System.out.println("Selected Image Writer can not compress! imageQuality is ignored!");
        }
        writer.write(null, new IIOImage(bi, null, null), iwparam);
    } finally {
        CloseUtils.safeClose(out);
        writer.dispose();
    }
}

From source file:org.deegree.securityproxy.wms.responsefilter.clipping.SimpleRasterClipper.java

private ImageWriteParam configureWriterParameters(String format, ImageWriter imageWriter) {
    ImageWriteParam writerParam = imageWriter.getDefaultWriteParam();
    if (JPG_FORMAT.equals(format)) {
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        writerParam.setCompressionQuality(1f);
    }/*www  .ja va 2s . co  m*/
    return writerParam;
}

From source file:org.egov.works.abstractestimate.service.EstimatePhotographService.java

public File compressImage(final MultipartFile[] files) throws IOException, FileNotFoundException {

    final BufferedImage image = ImageIO.read(files[0].getInputStream());
    final File compressedImageFile = new File(files[0].getOriginalFilename());
    final OutputStream os = new FileOutputStream(compressedImageFile);
    String fileExtenstion = files[0].getOriginalFilename();
    fileExtenstion = fileExtenstion.substring(fileExtenstion.lastIndexOf(".") + 1);
    final Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName(fileExtenstion);
    final ImageWriter writer = writers.next();
    final ImageOutputStream ios = ImageIO.createImageOutputStream(os);
    writer.setOutput(ios);/*w  w w  . java 2 s  .  c  om*/
    final ImageWriteParam param = writer.getDefaultWriteParam();

    if (!fileExtenstion.equalsIgnoreCase("png")) {
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.5f);
    }
    writer.write(null, new IIOImage(image, null, null), param);

    os.close();
    ios.close();
    writer.dispose();
    return compressedImageFile;
}

From source file:org.geotools.utils.coveragetiler.CoverageTiler.java

public void run() {

    // /////////////////////////////////////////////////////////////////////
    ////from  ww w . jav  a2 s  .c om
    //
    // Trying to acquire a reader for the provided source file.
    // 
    // 
    // /////////////////////////////////////////////////////////////////////
    StringBuilder message = new StringBuilder("Acquiring a reader to  ").append(inputLocation);
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);
    // get the format of this file, if it is recognized!
    final AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(inputLocation);
    if (format == null || format instanceof UnknownFormat) {
        fireException("Unable to decide format for this coverage", 0,
                new IOException("Could not find a format for this coverage"));
        return;
    }
    // get a reader for this file
    final AbstractGridCoverage2DReader inReader = (AbstractGridCoverage2DReader) format.getReader(inputLocation,
            new Hints(Hints.OVERVIEW_POLICY, OverviewPolicy.IGNORE));
    if (inReader == null) {
        message = new StringBuilder("Unable to instantiate a reader for this coverage");
        if (LOGGER.isLoggable(Level.WARNING))
            LOGGER.fine(message.toString());
        fireEvent(message.toString(), 0);
        return;
    }

    // /////////////////////////////////////////////////////////////////////
    //
    //
    // If everything went fine, let's proceed with tiling this coverage.
    // 
    // 
    // /////////////////////////////////////////////////////////////////////
    if (!outputLocation.exists())
        outputLocation.mkdir();

    // //
    //
    // getting source envelope and crs
    //
    // //
    final GeneralEnvelope envelope = inReader.getOriginalEnvelope();
    message = new StringBuilder("Original envelope is ").append(envelope.toString());
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    // //
    //
    // getting source gridrange and checking tile dimensions to be not
    // bigger than the original coverage size
    //
    // //
    final GridEnvelope range = inReader.getOriginalGridRange();
    final int w = range.getSpan(0);
    final int h = range.getSpan(1);
    tileWidth = tileWidth > w ? w : tileWidth;
    tileHeight = tileHeight > h ? h : tileHeight;
    message = new StringBuilder("Original range is ").append(range.toString());
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);
    message = new StringBuilder("New matrix dimension is (cols,rows)==(").append(tileWidth).append(",")
            .append(tileHeight).append(")");
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    // //
    //
    // read the coverage
    //
    // //
    GridCoverage2D gc;
    try {
        gc = (GridCoverage2D) inReader.read(null);
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        fireException(e);
        return;

    }

    // ///////////////////////////////////////////////////////////////////
    //
    // MAIN LOOP
    //
    //
    // ///////////////////////////////////////////////////////////////////
    final int numTileX = (int) (w / (tileWidth * 1.0) + 1);
    final int numTileY = (int) (h / (tileHeight * 1.0) + 1);
    for (int i = 0; i < numTileX; i++)
        for (int j = 0; j < numTileY; j++) {

            // //
            //
            // computing the bbox for this tile
            //
            // //
            final Rectangle sourceRegion = new Rectangle(i * tileWidth, j * tileHeight, tileWidth, tileHeight);
            message = new StringBuilder("Writing region  ").append(sourceRegion);
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.fine(message.toString());
            fireEvent(message.toString(), (i + j) / (numTileX * numTileY * 1.0));

            // //
            //
            // building gridgeometry for the read operation with the actual
            // envelope
            //
            // //
            final File fileOut = new File(outputLocation, new StringBuilder("mosaic").append("_")
                    .append(Integer.toString(i * tileWidth + j)).append(".").append("tiff").toString());
            // remove an old output file if it exists
            if (fileOut.exists())
                fileOut.delete();

            message = new StringBuilder("Preparing to write tile (col,row)==(").append(j).append(",").append(i)
                    .append(") to file ").append(fileOut);
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.fine(message.toString());
            fireEvent(message.toString(), (i + j) / (numTileX * numTileY * 1.0));

            // //
            //
            // Write this coverage out as a geotiff
            //
            // //
            GeoTiffWriter writerWI = null;
            try {

                final GeoTiffWriteParams wp = new GeoTiffWriteParams();
                wp.setTilingMode(GeoToolsWriteParams.MODE_EXPLICIT);
                wp.setTiling(internalTileWidth, internalTileHeight);
                wp.setSourceRegion(sourceRegion);
                if (this.compressionScheme != null && !Double.isNaN(compressionRatio)) {
                    wp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                    wp.setCompressionType(compressionScheme);
                    wp.setCompressionQuality((float) this.compressionRatio);
                }
                final ParameterValueGroup params = GEOTIFF_FORMAT.getWriteParameters();
                params.parameter(AbstractGridFormat.GEOTOOLS_WRITE_PARAMS.getName().toString()).setValue(wp);

                writerWI = new GeoTiffWriter(fileOut);
                writerWI.write(gc,
                        (GeneralParameterValue[]) params.values().toArray(new GeneralParameterValue[1]));

            } catch (IOException e) {
                fireException(e);
                return;
            } finally {
                if (writerWI != null) {
                    try {
                        writerWI.dispose();
                    } catch (Exception e) {
                        // eat me
                    }
                }
            }

        }

    message = new StringBuilder("Done...");
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 100);
}

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;
    ////ww  w  .j a  va2 s  . co  m
    // 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!!!");

}

From source file:org.geotools.utils.imagepyramid.PyramidLayerBuilder.java

public void run() {

    // /////////////////////////////////////////////////////////////////////
    ////from www .j  av  a 2 s.  c o  m
    //
    // PARSING INPUT PARAMETERS
    // 
    // 
    // /////////////////////////////////////////////////////////////////////
    StringBuilder message = new StringBuilder("Requested scale factor is ").append(scaleFactor);
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    // /////////////////////////////////////////////////////////////////////
    //
    //
    // Opening the base mosaic
    // 
    // 
    // /////////////////////////////////////////////////////////////////////
    // mosaic reader
    message = new StringBuilder("Acquiring a mosaic reader to mosaic ").append(inputLocation);
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    ImageMosaicReader inReader = null;
    try {
        inReader = new ImageMosaicReader(inputLocation,
                new Hints(Hints.OVERVIEW_POLICY, OverviewPolicy.IGNORE));
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        fireException(e);
        return;
    }

    // /////////////////////////////////////////////////////////////////////
    //
    //
    // Preparing all the params
    // 
    // 
    // /////////////////////////////////////////////////////////////////////
    // output files' directory
    if (!outputLocation.exists())
        outputLocation.mkdir();

    // getting envelope and other information about dimension
    final GeneralEnvelope envelope = inReader.getOriginalEnvelope();
    message = new StringBuilder("Original envelope is ").append(envelope.toString());
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    final GridEnvelope range = inReader.getOriginalGridRange();
    message = new StringBuilder("Original range is ").append(range.toString());
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    // new number of rows and columns
    final double newWidth = (range.getSpan(0) * 1.0) / scaleFactor;
    final double newHeight = (range.getSpan(1) * 1.0) / scaleFactor;
    if (tileW > newWidth)
        tileW = newWidth;
    if (tileH > newHeight)
        tileH = newHeight;

    message = new StringBuilder("New dimension is (W,H)==(").append(newWidth).append(",").append(newHeight)
            .append(")");
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    int newCols = (int) (newWidth / tileW);
    int newRows = (int) (newHeight / tileH);
    final boolean hasRemainingColum = (newWidth % tileW) != 0;
    final boolean hasRemainingRow = (newHeight % tileH) != 0;
    message = new StringBuilder("New matrix dimension is (cols,rows)==(").append(newCols).append(",")
            .append(newRows).append(")");
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 0);

    final double minx = envelope.getMinimum(0);
    final double miny = envelope.getMinimum(1);
    final double maxx = envelope.getMaximum(0);
    final double maxy = envelope.getMaximum(1);

    double _maxx = 0.0;
    double _maxy = 0.0;
    double _minx = 0.0;
    double _miny = 0.0;

    // ///////////////////////////////////////////////////////////////////
    //
    // MAIN LOOP
    //
    //
    // ///////////////////////////////////////////////////////////////////
    newRows += hasRemainingRow ? 1 : 0;
    newCols += hasRemainingColum ? 1 : 0;
    final double totalNumberOfFile = newRows * newCols;

    // getting resolution of each tile
    final double tileGeoWidth = envelope.getSpan(0) / newCols;
    final double tileGeoHeight = envelope.getSpan(1) / newRows;

    final int uppers[] = range.getHigh().getCoordinateValues();
    uppers[0]++;
    uppers[1]++;
    final double newRange[] = new double[] { uppers[0] / newCols, uppers[1] / newRows };
    final CoverageProcessor processor = CoverageProcessor.getInstance();
    for (int i = 0; i < newRows; i++)
        for (int j = 0; j < newCols; j++) {

            // //
            //
            // computing the bbox for this tile
            //
            // //
            _maxx = minx + (j + 1) * tileGeoWidth;
            _minx = minx + (j) * tileGeoWidth;
            _maxy = miny + (i + 1) * tileGeoHeight;
            _miny = miny + (i) * tileGeoHeight;
            if (_maxx > maxx)
                _maxx = maxx;
            if (_maxy > maxy)
                _maxy = maxy;

            // //
            //
            // creating the output file
            //
            // //
            final File fileOut = new File(outputLocation, new StringBuilder("mosaic").append("_")
                    .append(Integer.toString(i * newCols + j)).append(".").append("tiff").toString());
            if (fileOut.exists())
                fileOut.delete();

            message = new StringBuilder("Preparing tile (col,row)==(").append(j).append(",").append(i)
                    .append(") to file ").append(fileOut);
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.fine(message.toString());
            fireEvent(message.toString(), (j + i * newCols) / totalNumberOfFile);

            // //
            //
            // building gridgeometry for the read operation
            //
            // //
            final ParameterValue<GridGeometry2D> gg = ImageMosaicFormat.READ_GRIDGEOMETRY2D.createValue();
            final GeneralEnvelope cropEnvelope = new GeneralEnvelope(new double[] { _minx, _miny },
                    new double[] { _maxx, _maxy });
            cropEnvelope.setCoordinateReferenceSystem(inReader.getCrs());
            //we need to supply the requeste grid range but we use a fake one since we are using the ignore overviews switch 
            gg.setValue(new GridGeometry2D(new GridEnvelope2D(new Rectangle(0, 0, 800, 800)), cropEnvelope));
            message = new StringBuilder("Reading with grid envelope ").append(cropEnvelope.toString());
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.fine(message.toString());
            fireEvent(message.toString(), (j + i * newCols) / totalNumberOfFile);

            // //
            //
            // read the needed part and then crop to be sure that we have what we need
            //
            // //
            GridCoverage2D gc;
            try {
                gc = (GridCoverage2D) inReader.read(new GeneralParameterValue[] { gg });

            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
                fireEvent(e.getLocalizedMessage(), 0);
                return;
            }

            ParameterValueGroup param = processor.getOperation("CoverageCrop").getParameters();
            param.parameter("Source").setValue(gc);
            param.parameter("Envelope").setValue(cropEnvelope);
            param.parameter("ConserveEnvelope").setValue(Boolean.TRUE);
            final GridCoverage2D cropped = (GridCoverage2D) processor.doOperation(param);

            // //
            //
            // Adjusting the resolution in order to be the same as for all the others coverage
            //
            // //
            final GridEnvelope2D newGridrange = new GridEnvelope2D(
                    new Rectangle2D.Double(0.0, 0.0, newRange[0], newRange[1]).getBounds());
            final GridGeometry2D scaledGridGeometry = new GridGeometry2D(newGridrange, cropEnvelope);
            param = processor.getOperation("Resample").getParameters();
            param.parameter("Source").setValue(cropped);
            param.parameter("CoordinateReferenceSystem").setValue(inReader.getCrs());
            param.parameter("GridGeometry").setValue(scaledGridGeometry);
            param.parameter("InterpolationType")
                    .setValue(Interpolation.getInstance(Interpolation.INTERP_NEAREST));
            gc = (GridCoverage2D) processor.doOperation(param);

            message = new StringBuilder("Scaling...");
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.fine(message.toString());
            fireEvent(message.toString(), 0);

            if (scaleAlgorithm.equalsIgnoreCase("nn")) {
                param = processor.getOperation("Scale").getParameters();
                param.parameter("Source").setValue(gc);
                param.parameter("xScale").setValue(new Float(1.0 / scaleFactor));
                param.parameter("yScale").setValue(new Float(1.0 / scaleFactor));
                param.parameter("xTrans").setValue(new Float(0));
                param.parameter("yTrans").setValue(new Float(0));
                param.parameter("Interpolation")
                        .setValue(Interpolation.getInstance(Interpolation.INTERP_BILINEAR));
                gc = (GridCoverage2D) CoverageToolsConstants.SCALE_FACTORY.doOperation(param, new Hints());
            } else if (scaleAlgorithm.equalsIgnoreCase("filt")) {
                // scaling
                param = CoverageToolsConstants.FILTERED_SUBSAMPLE_FACTORY.getParameters();
                param.parameter("source").setValue(gc);
                param.parameter("scaleX").setValue(new Integer((int) scaleFactor));
                param.parameter("scaleY").setValue(new Integer((int) scaleFactor));
                param.parameter("qsFilterArray")
                        .setValue(new float[] { 0.5F, 1.0F / 3.0F, 0.0F, -1.0F / 12.0F });
                param.parameter("Interpolation").setValue(new InterpolationNearest());
                gc = (GridCoverage2D) CoverageToolsConstants.FILTERED_SUBSAMPLE_FACTORY.doOperation(param,
                        new Hints());
            } else if (scaleAlgorithm.equalsIgnoreCase("bil")) {
                param = processor.getOperation("Scale").getParameters();
                param.parameter("Source").setValue(gc);
                param.parameter("xScale").setValue(new Float(1.0 / scaleFactor));
                param.parameter("yScale").setValue(new Float(1.0 / scaleFactor));
                param.parameter("xTrans").setValue(new Float(0));
                param.parameter("yTrans").setValue(new Float(0));
                param.parameter("Interpolation")
                        .setValue(Interpolation.getInstance(Interpolation.INTERP_BILINEAR));
                gc = (GridCoverage2D) CoverageToolsConstants.SCALE_FACTORY.doOperation(param, new Hints());
            } else if (scaleAlgorithm.equalsIgnoreCase("avg")) {
                param = processor.getOperation("SubsampleAverage").getParameters();
                param.parameter("Source").setValue(gc);
                param.parameter("scaleX").setValue(new Double(1.0 / scaleFactor));
                param.parameter("scaleY").setValue(new Double(1.0 / scaleFactor));
                param.parameter("Interpolation").setValue(scaleFactor);
                gc = (GridCoverage2D) CoverageToolsConstants.SUBSAMPLE_AVERAGE_FACTORY.doOperation(param,
                        new Hints());
            } else
                throw new IllegalArgumentException("The provided scale algorithm is not availaible");

            // //
            //
            // Writing out this coverage
            //
            // //
            message = new StringBuilder("Writing out...");
            if (LOGGER.isLoggable(Level.FINE))
                LOGGER.fine(message.toString());
            fireEvent(message.toString(), (j + i * newCols) / totalNumberOfFile);

            try {

                final GeoTiffWriter writerWI = new GeoTiffWriter(fileOut);
                final GeoToolsWriteParams wp = ((AbstractGridFormat) writerWI.getFormat())
                        .getDefaultImageIOWriteParameters();
                if (this.compressionScheme != null) {
                    wp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                    wp.setCompressionType(this.compressionScheme);
                    wp.setCompressionQuality((float) this.compressionRatio);
                }
                wp.setTilingMode(ImageWriteParam.MODE_EXPLICIT);
                wp.setTiling(internalTileWidth, internalTileHeight, 0, 0);
                writerWI.write(gc, null);
                writerWI.dispose();

            } catch (IOException e) {
                LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
                fireEvent(e.getLocalizedMessage(), 0);
                return;
            }

        }

    message = new StringBuilder("Done...");
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine(message.toString());
    fireEvent(message.toString(), 100);

}

From source file:org.geowebcache.mime.FormatModifier.java

public synchronized ImageWriteParam adjustImageWriteParam(ImageWriteParam param) {
    if (imgWriteParam == null) {
        if (getCompressionQuality() != null) {
            if (getResponseFormat() == ImageMime.jpeg) {
                param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                param.setCompressionQuality(getCompressionQuality());
            } else {
                log.debug("FormatModifier only supports JPEG image parameters at this time.");
            }//from w ww.  ja  va 2 s .  c o m
        }
        imgWriteParam = param;
    }

    return imgWriteParam;
}

From source file:org.hippoecm.frontend.plugins.gallery.imageutil.ImageUtils.java

/**
 * Returns the data of a {@link BufferedImage} as a binary output stream. If the image is <code>null</code>,
 * a stream of zero bytes is returned./* w w w.  j  a  va  2s  . com*/
 *
 * @param writer the writer to use for writing the image data.
 * @param image the image to write.
 * @param compressionQuality a float between 0 and 1 that indicates the desired compression quality. Values lower than
 *                           0 will be interpreted as 0, values higher than 1 will be interpreted as 1.
 *
 * @return an output stream with the data of the given image.
 *
 * @throws IOException when creating the binary output stream failed.
 */
public static ByteArrayOutputStream writeImage(ImageWriter writer, BufferedImage image,
        float compressionQuality) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    if (image != null) {
        ImageOutputStream ios = null;
        try {
            ios = ImageIO.createImageOutputStream(out);
            writer.setOutput(ios);

            // write compressed images with high quality
            final ImageWriteParam writeParam = writer.getDefaultWriteParam();
            if (writeParam.canWriteCompressed()) {
                String[] compressionTypes = writeParam.getCompressionTypes();
                if (compressionTypes != null && compressionTypes.length > 0) {
                    writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
                    writeParam.setCompressionType(compressionTypes[0]);

                    // ensure a compression quality between 0 and 1
                    float trimmedCompressionQuality = Math.max(compressionQuality, 0);
                    trimmedCompressionQuality = Math.min(trimmedCompressionQuality, 1f);
                    writeParam.setCompressionQuality(trimmedCompressionQuality);
                }
            }

            final IIOImage iioImage = new IIOImage(image, null, null);
            writer.write(null, iioImage, writeParam);
            ios.flush();
        } finally {
            if (ios != null) {
                ios.close();
            }
        }
    }

    return out;
}

From source file:org.mycore.iview2.frontend.MCRTileCombineServlet.java

/**
 * Initializes this instance./*from  ww w . j a  v  a  2 s  . c  o  m*/
 * 
 * Use parameter <code>org.mycore.iview2.frontend.MCRFooterInterface</code> to specify implementation of {@link MCRFooterInterface} (can be omitted).
 */
@Override
public void init() throws ServletException {
    super.init();
    imageWriteParam = new JPEGImageWriteParam(Locale.getDefault());
    try {
        imageWriteParam.setProgressiveMode(ImageWriteParam.MODE_DEFAULT);
    } catch (UnsupportedOperationException e) {
        LOGGER.warn("Your JPEG encoder does not support progressive JPEGs.");
    }
    imageWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    imageWriteParam.setCompressionQuality(QUALITY);
    String footerClassName = getInitParameter(MCRFooterInterface.class.getName());
    if (footerClassName != null) {
        try {
            footerImpl = (MCRFooterInterface) Class.forName(footerClassName).newInstance();
        } catch (Exception e) {
            throw new ServletException("Could not initialize MCRFooterInterface", e);
        }
    }
}