Example usage for javax.imageio ImageReader setInput

List of usage examples for javax.imageio ImageReader setInput

Introduction

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

Prototype

public void setInput(Object input) 

Source Link

Document

Sets the input source to use to the given ImageInputStream or other Object .

Usage

From source file:org.dcm4che2.tool.dcm2dcm.Dcm2Dcm.java

/**
 * Recodes the images from the source transfer syntax, as read from the src
 * file, to the specified destination syntax.
 */// w w  w.ja v a 2  s  . c  om
public void recodeImages(File src, File dest) throws IOException {
    ImageReader reader = new DicomImageReaderSpi().createReaderInstance();
    ImageWriter writer = new DicomImageWriterSpi().createWriterInstance();

    DicomStreamMetaData writeMeta = (DicomStreamMetaData) writer.getDefaultStreamMetadata(null);

    DicomObject ds;
    int frames;

    FileImageOutputStream output = null;

    try {
        FileImageInputStream input = new FileImageInputStream(src);

        try {
            reader.setInput(input);
            if (dest.exists())
                dest.delete();
            output = new FileImageOutputStream(dest);
            writer.setOutput(output);
            DicomStreamMetaData streamMeta = (DicomStreamMetaData) reader.getStreamMetadata();
            ds = streamMeta.getDicomObject();

            DicomObject newDs = new BasicDicomObject();
            ds.copyTo(newDs);
            writeMeta.setDicomObject(newDs);
            frames = ds.getInt(Tag.NumberOfFrames, 1);
            newDs.putString(Tag.TransferSyntaxUID, VR.UI, destinationSyntax.uid());
            newDs.putString(Tag.ImplementationClassUID, VR.UI, Implementation.classUID());
            newDs.putString(Tag.ImplementationVersionName, VR.SH, Implementation.versionName());
            if (overwriteObject != null) {
                overwriteObject.copyTo(newDs);
            }
        } finally {
            reader.dispose();
        }
        writer.prepareWriteSequence(writeMeta);
        for (int i = 0; i < frames; i++) {
            FileInputStream inputStream = new FileInputStream(src);
            try {
                WritableRaster r = (WritableRaster) readRaster(inputStream, i);

                ColorModel cm = ColorModelFactory.createColorModel(ds);
                BufferedImage bi = new BufferedImage(cm, r, false, null);
                IIOImage iioimage = new IIOImage(bi, null, null);
                writer.writeToSequence(iioimage, null);
            } catch (NoSuchFieldException ex) {
                System.err.println(ex.toString());
            } catch (IllegalAccessException ex) {
                System.err.println(ex.toString());
            } finally {
                inputStream.close();
            }
        }
        writer.endWriteSequence();
    } finally {
        if (output != null) {
            output.close();
        }
    }
}

From source file:org.paxle.gui.impl.servlets.ConfigView.java

public void writeImage(HttpServletRequest request, HttpServletResponse response, Context context)
        throws Exception {
    final String pid = request.getParameter("pid");
    if (pid == null) {
        response.sendError(501, "No pid supplied.");
        return;/*w  w w .j  a v  a2  s.  c  om*/
    }

    final String bundleID = request.getParameter("bundleID");
    if (bundleID == null) {
        response.sendError(501, "No bundle-ID supplied.");
        return;
    }

    final ConfigTool configTool = (ConfigTool) context.get(ConfigTool.TOOL_NAME);
    if (configTool == null) {
        response.sendError(501, "Config-Tool not found.");
        return;
    }

    final Configurable configurabel = configTool.getConfigurable(Integer.valueOf(bundleID), pid);
    if (configurabel == null) {
        response.sendError(501, String
                .format("No configurable component found for bundle-ID '%s' and PID '%s'.", bundleID, pid));
        return;
    }

    // loading metadata
    final ObjectClassDefinition ocd = configurabel.getObjectClassDefinition();
    if (ocd == null) {
        response.sendError(501,
                String.format("No ObjectClassDefinition found for service with PID '%s'.", pid));
        return;
    }

    try {
        // trying to find a proper icon
        final int[] sizes = new int[] { 16, 32, 64, 128, 256 };

        BufferedImage img = null;
        for (int size : sizes) {
            // trying to find an icon
            InputStream in = ocd.getIcon(size);
            if (in == null) {
                if (size == sizes[sizes.length - 1]) {
                    // fallback to the default image
                    in = this.getClass().getResourceAsStream("/resources/images/cog.png");
                } else
                    continue;
            }

            // loading date
            final ByteArrayOutputStream bout = new ByteArrayOutputStream();
            IOUtils.copy(in, bout);
            bout.close();
            in.close();

            // trying to detect the mimetype of the image
            ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            String contentType = URLConnection.guessContentTypeFromStream(bin);
            bin.close();

            Iterator<ImageReader> readers = null;
            if (contentType != null) {
                readers = ImageIO.getImageReadersByMIMEType(contentType);
            } else {
                readers = ImageIO.getImageReadersByFormatName("png");
            }

            while (readers.hasNext() && img == null) {
                // trying the next reader
                final ImageReader reader = readers.next();

                InputStream input = null;
                try {
                    input = new ByteArrayInputStream(bout.toByteArray());
                    reader.setInput(ImageIO.createImageInputStream(input));
                    img = reader.read(0);
                } catch (Exception e) {
                    this.log("Unable to read image for pid " + pid, e);
                } finally {
                    if (input != null)
                        input.close();
                }
            }

            if (img != null) {
                response.setHeader("Content-Type", "image/png");
                ImageIO.write(img, "png", response.getOutputStream());
                return;
            }
        }

        // no icon found. 
        response.sendError(404);
    } catch (Throwable e) {
        response.sendError(404, e.getMessage());
        return;
    }
}

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

/**
 * Creates a scaled version of an image. The given scaling parameters define a bounding box with a certain width and
 * height. Images that do not fit in this box (i.e. are too large) are always scaled down such that they do fit. If
 * the aspect ratio of the original image differs from that of the bounding box, either the width or the height of
 * scaled image will be less than that of the box.</p> <p> Smaller images are scaled up in the same way as large
 * images are scaled down, but only if upscaling is true. When upscaling is false and the image is smaller than the
 * bounding box, the scaled image will be equal to the original.</p> <p> If the width or height of the scaling
 * parameters is 0 or less, that side of the bounding box does not exist (i.e. is unbounded). If both sides of the
 * bounding box are unbounded, the scaled image will be equal to the original.</p>
 *
 * @param data   the original image data
 * @param reader reader for the image data
 * @param writer writer for the image data
 *//*w w  w.j a  v  a2 s .  co  m*/
public void execute(InputStream data, ImageReader reader, ImageWriter writer) throws IOException {
    // save the image data in a temporary file so we can reuse the original data as-is if needed without
    // putting all the data into memory
    final File tmpFile = writeToTmpFile(data);
    boolean deleteTmpFile = true;
    log.debug("Stored uploaded image in temporary file {}", tmpFile);

    InputStream dataInputStream = null;
    ImageInputStream imageInputStream = null;

    try {
        dataInputStream = new FileInputStream(tmpFile);
        imageInputStream = new MemoryCacheImageInputStream(dataInputStream);
        reader.setInput(imageInputStream);

        final int originalWidth = reader.getWidth(0);
        final int originalHeight = reader.getHeight(0);

        if (isOriginalVariant()) {
            scaledWidth = originalWidth;
            scaledHeight = originalHeight;
            scaledData = new AutoDeletingTmpFileInputStream(tmpFile);
            deleteTmpFile = false;
        } else {
            BufferedImage scaledImage = getScaledImage(reader, originalWidth, originalHeight);
            ByteArrayOutputStream scaledOutputStream = ImageUtils.writeImage(writer, scaledImage,
                    compressionQuality);

            scaledWidth = scaledImage.getWidth();
            scaledHeight = scaledImage.getHeight();
            scaledData = new ByteArrayInputStream(scaledOutputStream.toByteArray());
        }
    } finally {
        if (imageInputStream != null) {
            imageInputStream.close();
        }
        IOUtils.closeQuietly(dataInputStream);
        if (deleteTmpFile) {
            log.debug("Deleting temporary file {}", tmpFile);
            tmpFile.delete();
        }
    }
}

From source file:org.freecine.filmscan.ScanStrip.java

/**
 Load the scan strip image from disk/*  w  w  w. j  a v  a  2s.co  m*/
 */
private void loadImage() {
    ImageReader reader;
    try {
        //        PlanarImage img = JAI.create( "fileload", fname );
        ImageInputStream istrm = new FileImageInputStream(file);
        reader = ImageIO.getImageReadersByFormatName("TIFF").next();
        reader.setInput(istrm);
        ImageReadParam param = reader.getDefaultReadParam();

        /*
         Set the color mode to linear sRGB as we don't have a better profile
         for the scanner/film available
         */
        ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_LINEAR_RGB);
        ImageLayout layout = new ImageLayout();
        ColorModel cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, DataBuffer.TYPE_USHORT);
        layout.setColorModel(cm);
        RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
        stripImage = ImageReadDescriptor.create(istrm, 0, false, false, false, null, null, param, reader,
                hints);
        System.out.println("Color model " + stripImage.getColorModel());
        // BufferedImage inImg = reader.read( 0, param );            
    } catch (FileNotFoundException ex) {
        System.out.println(ex.getMessage());
        log.error("Strip file " + file + " not found", ex);
    } catch (IOException ex) {
        log.error("IO error reading strip " + file + ": ", ex);
    }
}

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

/**
 * Main thread for the mosaic index builder.
 *///from   w  w w  .j  a  v a2  s .  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.xwiki.contrib.ldap.XWikiLDAPUtils.java

/**
 * Guess image type of InputStream.//  ww  w . j  a  v  a  2 s  . c  o m
 * 
 * @param imageInputStream InputStream containing image.
 * @return type of image as String.
 */
protected String guessImageType(InputStream imageInputStream) {
    ImageInputStream imageStream;
    try {
        imageStream = ImageIO.createImageInputStream(imageInputStream);
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage());
        return null;
    }

    Iterator<ImageReader> it = ImageIO.getImageReaders(imageStream);
    if (!it.hasNext()) {
        LOGGER.warn("No image readers found for provided stream.");
        return null;
    }

    ImageReader imageReader = it.next();
    imageReader.setInput(imageStream);

    try {
        return imageReader.getFormatName();
    } catch (IOException ex) {
        LOGGER.error(ex.getMessage());
        return null;
    } finally {
        imageReader.dispose();
    }
}

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;
    ///*from w w w.  jav a 2  s .c o 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:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

private IIOImage createImage(InputStream istr, int attempt) throws ImageInterpreterException {
    ImageInputStream iis = null;/*from ww w .j  av a  2 s . c  o m*/
    Iterator<ImageReader> ri = null;
    ImageReadParam param = null;
    ImageReader ir = null;
    BufferedImage bi = null;
    // Raster raster = null;
    // int[] bufferTypes = new int[] { DataBuffer.TYPE_BYTE, DataBuffer.TYPE_INT, DataBuffer.TYPE_FLOAT, DataBuffer.TYPE_DOUBLE,
    // DataBuffer.TYPE_SHORT, DataBuffer.TYPE_USHORT, DataBuffer.TYPE_UNDEFINED };

    // Create raster from image reader
    try {
        iis = ImageIO.createImageInputStream(istr);
        ri = ImageIO.getImageReaders(iis);
        if (!ri.hasNext()) {
            // List<ImageReader> list = new ArrayList<ImageReader>();
            // list.add(new JPEGImageReader(new JPEGImageReaderSpi()));
            ri = IteratorUtils.getIterator(new JPEGImageReader(new JPEGImageReaderSpi()));
        }
    } catch (IOException e) {
        throw new ImageInterpreterException("Error reading input stream: " + e.toString());
    }
    while (ri.hasNext()) {
        ir = ri.next();
        try {
            ir.setInput(iis);
            param = ir.getDefaultReadParam();
            bi = ir.read(0, param);
            // raster = ir.readRaster(0, param);
            if (bi != null) {
                break;
            }
        } catch (Error e) {
            LOGGER.error("Failed to render image with ImageReader: " + e.toString());
            continue;
        } catch (Exception e) {
            LOGGER.error("Failed to render image with ImageReader: " + e.toString());
            continue;
        }
    }

    // store metadata
    IIOMetadata md = null;
    try {
        md = getImageMetadata(ir);
    } catch (ImageInterpreterException e) {
        LOGGER.error("Failed to extract metadata from image: " + e.getMessage());
        InputStream patchedInputStream = null;
        if (attempt <= 1) {
            patchedInputStream = attempt == 0 ? new PatchInputStream(istr) : new RemoveHeaderInputStream(istr);
            if (istr != null) {
                try {
                    istr.close();
                } catch (IOException e1) {
                    LOGGER.error("Failed to close input stream");
                }
            }
            return createImage(patchedInputStream, attempt + 1);
        } else {
            LOGGER.error("Unable to read image metadata.");
            md = null;
        }
    } finally {
        if (iis != null) {
            try {
                iis.close();
            } catch (IOException e) {
                LOGGER.error("Failed to close image stream", e);
            }
        }
    }

    // // create buffered image from raster
    // int count = 0;
    // while (count < bufferTypes.length) {
    // int bufferType = bufferTypes[count++];
    // try {
    // SampleModel sm = RasterFactory.createPixelInterleavedSampleModel(bufferType, raster.getWidth(), raster.getHeight(),
    // raster.getNumBands());
    // ColorModel cm = PlanarImage.createColorModel(sm);
    // // cm = bi.getColorModel();
    // ColorSpace sourceColorSpace = cm.getColorSpace();
    // ColorSpace destColorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    // ColorConvertOp op = new ColorConvertOp(sourceColorSpace, destColorSpace, null);
    // // WritableRaster wraster = raster.createInterleavedRaster(bufferTypes[count-1], raster.getWidth(), raster.getHeight(),
    // raster.getNumBands(), null);
    // // WritableRaster wraster = op.createCompatibleDestRaster(raster);
    // WritableRaster wraster = op.filter(raster, null);
    // // Raster raster2 = bi.getRaster();
    // // cm = new ComponentColorModel(cs, false, false, ColorModel.OPAQUE, bufferType);
    // // sm = bi.getSampleModel();
    // // cm = bi.getColorModel();
    // // cm = ColorModel.getRGBdefault();
    // bi = new BufferedImage(cm, wraster, false, null);
    // cm.finalize();
    // } catch (Error e) {
    // LOGGER.debug("Failed to render image with BufferType " + bufferType);
    // continue;
    // } catch (Exception e) {
    // LOGGER.debug("Failed to render image with BufferType " + bufferType);
    // continue;
    // }
    // break;
    // }

    if (bi == null) {
        throw new ImageInterpreterException("Failed to extract buffered image from image reader");
    }
    IIOImage image = new IIOImage(bi, null, md);
    return image;
}

From source file:org.geotools.gce.imagemosaic.GranuleDescriptor.java

/**
* Load a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* 
* @param imageReadParameters the {@link ImageReadParam} to use for reading.
* @param index the index to use for the {@link ImageReader}.
* @param cropBBox the bbox to use for cropping. 
* @param mosaicWorldToGrid the cropping grid to world transform.
* @param request the incoming request to satisfy.
* @param hints {@link Hints} to be used for creating this raster.
* @return a specified a raster as a portion of the granule describe by this {@link GranuleDescriptor}.
* @throws IOException in case an error occurs.
*//*w  w  w  .j  a  va  2s.c o m*/
public GranuleLoadingResult loadRaster(final ImageReadParam imageReadParameters, final int index,
        final ReferencedEnvelope cropBBox, final MathTransform2D mosaicWorldToGrid,
        final RasterLayerRequest request, final Hints hints) throws IOException {

    if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
        final String name = Thread.currentThread().getName();
        LOGGER.finer("Thread:" + name + " Loading raster data for granuleDescriptor " + this.toString());
    }
    ImageReadParam readParameters = null;
    int imageIndex;
    final boolean useFootprint = roiProvider != null
            && request.getFootprintBehavior() != FootprintBehavior.None;
    Geometry inclusionGeometry = useFootprint ? roiProvider.getFootprint() : null;
    final ReferencedEnvelope bbox = useFootprint
            ? new ReferencedEnvelope(granuleBBOX.intersection(inclusionGeometry.getEnvelopeInternal()),
                    granuleBBOX.getCoordinateReferenceSystem())
            : granuleBBOX;
    boolean doFiltering = false;
    if (filterMe && useFootprint) {
        doFiltering = Utils.areaIsDifferent(inclusionGeometry, baseGridToWorld, granuleBBOX);
    }

    // intersection of this tile bound with the current crop bbox
    final ReferencedEnvelope intersection = new ReferencedEnvelope(bbox.intersection(cropBBox),
            cropBBox.getCoordinateReferenceSystem());
    if (intersection.isEmpty()) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    // check if the requested bbox intersects or overlaps the requested area 
    if (useFootprint && inclusionGeometry != null && !JTS.toGeometry(cropBBox).intersects(inclusionGeometry)) {
        if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
            LOGGER.fine(new StringBuilder("Got empty intersection for granule ").append(this.toString())
                    .append(" with request ").append(request.toString())
                    .append(" Resulting in no granule loaded: Empty result").toString());
        }
        return null;
    }

    ImageInputStream inStream = null;
    ImageReader reader = null;
    try {
        //
        //get info about the raster we have to read
        //

        // get a stream
        assert cachedStreamSPI != null : "no cachedStreamSPI available!";
        inStream = cachedStreamSPI.createInputStreamInstance(granuleUrl, ImageIO.getUseCache(),
                ImageIO.getCacheDirectory());
        if (inStream == null)
            return null;

        // get a reader and try to cache the relevant SPI
        if (cachedReaderSPI == null) {
            reader = ImageIOExt.getImageioReader(inStream);
            if (reader != null)
                cachedReaderSPI = reader.getOriginatingProvider();
        } else
            reader = cachedReaderSPI.createReaderInstance();
        if (reader == null) {
            if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
                LOGGER.warning(new StringBuilder("Unable to get s reader for granuleDescriptor ")
                        .append(this.toString()).append(" with request ").append(request.toString())
                        .append(" Resulting in no granule loaded: Empty result").toString());
            }
            return null;
        }
        // set input
        customizeReaderInitialization(reader, hints);
        reader.setInput(inStream);

        // Checking for heterogeneous granules
        if (request.isHeterogeneousGranules()) {
            // create read parameters
            readParameters = new ImageReadParam();

            //override the overviews controller for the base layer
            imageIndex = ReadParamsController.setReadParams(
                    request.spatialRequestHelper.getRequestedResolution(), request.getOverviewPolicy(),
                    request.getDecimationPolicy(), readParameters, request.rasterManager, overviewsController);
        } else {
            imageIndex = index;
            readParameters = imageReadParameters;
        }

        //get selected level and base level dimensions
        final GranuleOverviewLevelDescriptor selectedlevel = getLevel(imageIndex, reader);

        // now create the crop grid to world which can be used to decide
        // which source area we need to crop in the selected level taking
        // into account the scale factors imposed by the selection of this
        // level together with the base level grid to world transformation
        AffineTransform2D cropWorldToGrid = new AffineTransform2D(selectedlevel.gridToWorldTransformCorner);
        cropWorldToGrid = (AffineTransform2D) cropWorldToGrid.inverse();
        // computing the crop source area which lives into the
        // selected level raster space, NOTICE that at the end we need to
        // take into account the fact that we might also decimate therefore
        // we cannot just use the crop grid to world but we need to correct
        // it.
        final Rectangle sourceArea = CRS.transform(cropWorldToGrid, intersection).toRectangle2D().getBounds();
        //gutter
        if (selectedlevel.baseToLevelTransform.isIdentity()) {
            sourceArea.grow(2, 2);
        }
        XRectangle2D.intersect(sourceArea, selectedlevel.rasterDimensions, sourceArea);//make sure roundings don't bother us
        // is it empty??
        if (sourceArea.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.fine("Got empty area for granuleDescriptor " + this.toString() + " with request "
                        + request.toString() + " Resulting in no granule loaded: Empty result");

            }
            return null;

        } else if (LOGGER.isLoggable(java.util.logging.Level.FINER)) {
            LOGGER.finer("Loading level " + imageIndex + " with source region: " + sourceArea + " subsampling: "
                    + readParameters.getSourceXSubsampling() + "," + readParameters.getSourceYSubsampling()
                    + " for granule:" + granuleUrl);
        }

        // Setting subsampling 
        int newSubSamplingFactor = 0;
        final String pluginName = cachedReaderSPI.getPluginClassName();
        if (pluginName != null && pluginName.equals(ImageUtilities.DIRECT_KAKADU_PLUGIN)) {
            final int ssx = readParameters.getSourceXSubsampling();
            final int ssy = readParameters.getSourceYSubsampling();
            newSubSamplingFactor = ImageIOUtilities.getSubSamplingFactor2(ssx, ssy);
            if (newSubSamplingFactor != 0) {
                if (newSubSamplingFactor > maxDecimationFactor && maxDecimationFactor != -1) {
                    newSubSamplingFactor = maxDecimationFactor;
                }
                readParameters.setSourceSubsampling(newSubSamplingFactor, newSubSamplingFactor, 0, 0);
            }
        }

        // set the source region
        readParameters.setSourceRegion(sourceArea);
        RenderedImage raster;
        try {
            // read
            raster = request.getReadType().read(readParameters, imageIndex, granuleUrl,
                    selectedlevel.rasterDimensions, reader, hints, false);

        } catch (Throwable e) {
            if (LOGGER.isLoggable(java.util.logging.Level.FINE)) {
                LOGGER.log(java.util.logging.Level.FINE,
                        "Unable to load raster for granuleDescriptor " + this.toString() + " with request "
                                + request.toString() + " Resulting in no granule loaded: Empty result",
                        e);
            }
            return null;
        }

        // use fixed source area
        sourceArea.setRect(readParameters.getSourceRegion());

        //
        // setting new coefficients to define a new affineTransformation
        // to be applied to the grid to world transformation
        // -----------------------------------------------------------------------------------
        //
        // With respect to the original envelope, the obtained planarImage
        // needs to be rescaled. The scaling factors are computed as the
        // ratio between the cropped source region sizes and the read
        // image sizes.
        //
        // place it in the mosaic using the coords created above;
        double decimationScaleX = ((1.0 * sourceArea.width) / raster.getWidth());
        double decimationScaleY = ((1.0 * sourceArea.height) / raster.getHeight());
        final AffineTransform decimationScaleTranform = XAffineTransform.getScaleInstance(decimationScaleX,
                decimationScaleY);

        // keep into account translation  to work into the selected level raster space
        final AffineTransform afterDecimationTranslateTranform = XAffineTransform
                .getTranslateInstance(sourceArea.x, sourceArea.y);

        // now we need to go back to the base level raster space
        final AffineTransform backToBaseLevelScaleTransform = selectedlevel.baseToLevelTransform;

        // now create the overall transform
        final AffineTransform finalRaster2Model = new AffineTransform(baseGridToWorld);
        finalRaster2Model.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if (!XAffineTransform.isIdentity(backToBaseLevelScaleTransform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(backToBaseLevelScaleTransform);
        if (!XAffineTransform.isIdentity(afterDecimationTranslateTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(afterDecimationTranslateTranform);
        if (!XAffineTransform.isIdentity(decimationScaleTranform, Utils.AFFINE_IDENTITY_EPS))
            finalRaster2Model.concatenate(decimationScaleTranform);

        // adjust roi
        if (useFootprint) {

            ROIGeometry transformed;
            try {
                transformed = roiProvider.getTransformedROI(finalRaster2Model.createInverse());
                if (transformed.getAsGeometry().isEmpty()) {
                    // inset might have killed the geometry fully
                    return null;
                }

                PlanarImage pi = PlanarImage.wrapRenderedImage(raster);
                if (!transformed.intersects(pi.getBounds())) {
                    return null;
                }
                pi.setProperty("ROI", transformed);
                raster = pi;

            } catch (NoninvertibleTransformException e) {
                if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                    LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                            + " due to a problem when managing the ROI");
                return null;
            }

        }
        // keep into account translation factors to place this tile
        finalRaster2Model.preConcatenate((AffineTransform) mosaicWorldToGrid);
        final Interpolation interpolation = request.getInterpolation();

        //paranoiac check to avoid that JAI freaks out when computing its internal layouT on images that are too small
        Rectangle2D finalLayout = ImageUtilities.layoutHelper(raster, (float) finalRaster2Model.getScaleX(),
                (float) finalRaster2Model.getScaleY(), (float) finalRaster2Model.getTranslateX(),
                (float) finalRaster2Model.getTranslateY(), interpolation);
        if (finalLayout.isEmpty()) {
            if (LOGGER.isLoggable(java.util.logging.Level.INFO))
                LOGGER.info("Unable to create a granuleDescriptor " + this.toString()
                        + " due to jai scale bug creating a null source area");
            return null;
        }

        // apply the affine transform  conserving indexed color model
        final RenderingHints localHints = new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL,
                interpolation instanceof InterpolationNearest ? Boolean.FALSE : Boolean.TRUE);
        if (XAffineTransform.isIdentity(finalRaster2Model, Utils.AFFINE_IDENTITY_EPS)) {
            return new GranuleLoadingResult(raster, null, granuleUrl, doFiltering, pamDataset);
        } else {
            //
            // In case we are asked to use certain tile dimensions we tile
            // also at this stage in case the read type is Direct since
            // buffered images comes up untiled and this can affect the
            // performances of the subsequent affine operation.
            //
            final Dimension tileDimensions = request.getTileDimensions();
            if (tileDimensions != null && request.getReadType().equals(ReadType.DIRECT_READ)) {
                final ImageLayout layout = new ImageLayout();
                layout.setTileHeight(tileDimensions.width).setTileWidth(tileDimensions.height);
                localHints.add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout));
            } else {
                if (hints != null && hints.containsKey(JAI.KEY_IMAGE_LAYOUT)) {
                    final Object layout = hints.get(JAI.KEY_IMAGE_LAYOUT);
                    if (layout != null && layout instanceof ImageLayout) {
                        localHints
                                .add(new RenderingHints(JAI.KEY_IMAGE_LAYOUT, ((ImageLayout) layout).clone()));
                    }
                }
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_CACHE)) {
                final Object cache = hints.get(JAI.KEY_TILE_CACHE);
                if (cache != null && cache instanceof TileCache)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, (TileCache) cache));
            }
            if (hints != null && hints.containsKey(JAI.KEY_TILE_SCHEDULER)) {
                final Object scheduler = hints.get(JAI.KEY_TILE_SCHEDULER);
                if (scheduler != null && scheduler instanceof TileScheduler)
                    localHints.add(new RenderingHints(JAI.KEY_TILE_SCHEDULER, (TileScheduler) scheduler));
            }
            boolean addBorderExtender = true;
            if (hints != null && hints.containsKey(JAI.KEY_BORDER_EXTENDER)) {
                final Object extender = hints.get(JAI.KEY_BORDER_EXTENDER);
                if (extender != null && extender instanceof BorderExtender) {
                    localHints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER, (BorderExtender) extender));
                    addBorderExtender = false;
                }
            }
            // BORDER extender
            if (addBorderExtender) {
                localHints.add(ImageUtilities.BORDER_EXTENDER_HINTS);
            }

            ImageWorker iw = new ImageWorker(raster);
            iw.setRenderingHints(localHints);
            iw.affine(finalRaster2Model, interpolation, request.getBackgroundValues());
            return new GranuleLoadingResult(iw.getRenderedImage(), null, granuleUrl, doFiltering, pamDataset);
        }

    } catch (IllegalStateException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (org.opengis.referencing.operation.NoninvertibleTransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;
    } catch (TransformException e) {
        if (LOGGER.isLoggable(java.util.logging.Level.WARNING)) {
            LOGGER.log(java.util.logging.Level.WARNING,
                    new StringBuilder("Unable to load raster for granuleDescriptor ").append(this.toString())
                            .append(" with request ").append(request.toString())
                            .append(" Resulting in no granule loaded: Empty result").toString(),
                    e);
        }
        return null;

    } finally {
        try {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && inStream != null) {
                inStream.close();
            }
        } finally {
            if (request.getReadType() != ReadType.JAI_IMAGEREAD && reader != null) {
                reader.dispose();
            }
        }
    }
}