Example usage for java.awt.geom AffineTransform getTranslateX

List of usage examples for java.awt.geom AffineTransform getTranslateX

Introduction

In this page you can find the example usage for java.awt.geom AffineTransform getTranslateX.

Prototype

public double getTranslateX() 

Source Link

Document

Returns the X coordinate of the translation element (m02) of the 3x3 affine transformation matrix.

Usage

From source file:com.t_oster.visicut.misc.Helper.java

/**
* Compute the rotation angle of an affine transformation.
* Counter-clockwise rotation is considered positive.
*
* method taken from http://javagraphics.blogspot.com/
*
* @return rotation angle in radians (beween -pi and pi),
*  or NaN if the transformation is bogus.
*//*from ww  w .j  a  v a  2s .  c  o  m*/
public static double getRotationAngle(AffineTransform transform) {
    transform = (AffineTransform) transform.clone();
    // Eliminate any post-translation
    transform.preConcatenate(
            AffineTransform.getTranslateInstance(-transform.getTranslateX(), -transform.getTranslateY()));
    Point2D p1 = new Point2D.Double(1, 0);
    p1 = transform.transform(p1, p1);
    return Math.atan2(p1.getY(), p1.getX());
}

From source file:Main.java

public void paint(Graphics g) {
    Shape shape = new Rectangle2D.Float(100, 50, 80, 80);

    Graphics2D g2 = (Graphics2D) g;

    AffineTransform at = new AffineTransform();
    at.setToQuadrantRotation(2, 0.5, 0.5);

    System.out.println(at.getTranslateX());

    g2.setTransform(at);/*from  w  w w.  j ava2s.  c  om*/
    g2.draw(shape);

}

From source file:es.ucm.fdi.edd.ui.views.utils.SWTImageCanvas.java

private void scrollHorizontally(ScrollBar scrollBar) {
    if (sourceImage == null)
        return;//from w  w w.  j a va 2  s . c o  m

    AffineTransform af = transform;
    double tx = af.getTranslateX();
    double select = -scrollBar.getSelection();
    af.preConcatenate(AffineTransform.getTranslateInstance(select - tx, 0));
    transform = af;
    syncScrollBars();
}

From source file:Matrix.java

/**
 * Set the values of the matrix from the AffineTransform.
 * /* www .jav  a 2  s.c  om*/
 * @param af The transform to get the values from.
 */
public void setFromAffineTransform(AffineTransform af) {
    single[0] = (float) af.getScaleX();
    single[1] = (float) af.getShearY();
    single[3] = (float) af.getShearX();
    single[4] = (float) af.getScaleY();
    single[6] = (float) af.getTranslateX();
    single[7] = (float) af.getTranslateY();
}

From source file:es.ucm.fdi.edd.ui.views.utils.SWTImageCanvas.java

/**
 * Synchronize the scrollbar with the image. If the transform is out of
 * range, it will correct it. This function considers only following factors
 * :<b> transform, image size, client area</b>.
 *///from  w w w . j  a  va  2s .  c om
public void syncScrollBars() {
    if (sourceImage == null) {
        redraw();
        return;
    }

    AffineTransform af = transform;
    double sx = af.getScaleX(), sy = af.getScaleY();
    double tx = af.getTranslateX(), ty = af.getTranslateY();
    if (tx > 0)
        tx = 0;
    if (ty > 0)
        ty = 0;

    ScrollBar horizontal = getHorizontalBar();
    horizontal.setIncrement((int) (getClientArea().width / 100));
    horizontal.setPageIncrement(getClientArea().width);
    Rectangle imageBound = sourceImage.getBounds();
    int cw = getClientArea().width, ch = getClientArea().height;
    if (imageBound.width * sx > cw) { /* image is wider than client area */
        horizontal.setMaximum((int) (imageBound.width * sx));
        horizontal.setEnabled(true);
        if (((int) -tx) > horizontal.getMaximum() - cw)
            tx = -horizontal.getMaximum() + cw;
    } else { /* image is narrower than client area */
        horizontal.setEnabled(false);
        tx = (cw - imageBound.width * sx) / 2; // center if too small.
    }
    horizontal.setSelection((int) (-tx));
    horizontal.setThumb((int) (getClientArea().width));

    ScrollBar vertical = getVerticalBar();
    vertical.setIncrement((int) (getClientArea().height / 100));
    vertical.setPageIncrement((int) (getClientArea().height));
    if (imageBound.height * sy > ch) { /* image is higher than client area */
        vertical.setMaximum((int) (imageBound.height * sy));
        vertical.setEnabled(true);
        if (((int) -ty) > vertical.getMaximum() - ch)
            ty = -vertical.getMaximum() + ch;
    } else { /* image is less higher than client area */
        vertical.setEnabled(false);
        ty = (ch - imageBound.height * sy) / 2; // center if too small.
    }
    vertical.setSelection((int) (-ty));
    vertical.setThumb((int) (getClientArea().height));

    /* update transform. */
    af = AffineTransform.getScaleInstance(sx, sy);
    af.preConcatenate(AffineTransform.getTranslateInstance(tx, ty));
    transform = af;

    redraw();
}

From source file:org.apache.fop.afp.AFPGraphics2D.java

/** {@inheritDoc} */
@Override/*from   w  w  w  .  ja  v  a 2s  . com*/
public void drawRenderedImage(RenderedImage img, AffineTransform xform) {
    int imgWidth = img.getWidth();
    int imgHeight = img.getHeight();

    AffineTransform gat = gc.getTransform();
    int graphicsObjectHeight = graphicsObj.getObjectEnvironmentGroup().getObjectAreaDescriptor().getHeight();

    double toMillipointFactor = UnitConv.IN2PT * 1000 / (double) paintingState.getResolution();
    double x = gat.getTranslateX();
    double y = -(gat.getTranslateY() - graphicsObjectHeight);
    x = toMillipointFactor * x;
    y = toMillipointFactor * y;
    double w = toMillipointFactor * imgWidth * gat.getScaleX();
    double h = toMillipointFactor * imgHeight * -gat.getScaleY();

    AFPImageHandlerRenderedImage handler = new AFPImageHandlerRenderedImage();
    ImageInfo imageInfo = new ImageInfo(null, null);
    imageInfo.setSize(new ImageSize(img.getWidth(), img.getHeight(), paintingState.getResolution()));
    imageInfo.getSize().calcSizeFromPixels();
    ImageRendered red = new ImageRendered(imageInfo, img, null);
    Rectangle targetPos = new Rectangle((int) Math.round(x), (int) Math.round(y), (int) Math.round(w),
            (int) Math.round(h));
    AFPRenderingContext context = new AFPRenderingContext(null, resourceManager, paintingState, fontInfo, null);
    try {
        handler.handleImage(context, red, targetPos);
    } catch (IOException ioe) {
        handleIOException(ioe);
    }
}

From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java

private void moveAnnotations(PDPage page, List pageAnnotations, AffineTransform at) {
    PDRectangle mediaBox = page.getMediaBox();
    PDRectangle cropBox = page.getCropBox();
    PDRectangle viewBox = cropBox != null ? cropBox : mediaBox;
    for (Object obj : pageAnnotations) {
        PDAnnotation annot = (PDAnnotation) obj;
        PDRectangle rect = annot.getRectangle();
        float translateX = (float) (at.getTranslateX() - viewBox.getLowerLeftX());
        float translateY = (float) (at.getTranslateY() - viewBox.getLowerLeftY());
        if (rect != null) {
            rect.setUpperRightX(rect.getUpperRightX() + translateX);
            rect.setLowerLeftX(rect.getLowerLeftX() + translateX);
            rect.setUpperRightY(rect.getUpperRightY() + translateY);
            rect.setLowerLeftY(rect.getLowerLeftY() + translateY);
            annot.setRectangle(rect);//from www .  j  a  va  2  s.  c o  m
        }
        //            COSArray vertices = (COSArray) annot.getCOSObject().getDictionaryObject("Vertices");
        //            if (vertices != null) {
        //                Iterator iter = vertices.iterator();
        //                while (iter.hasNext()) {
        //                    COSFloat x = (COSFloat) iter.next();
        //                    COSFloat y = (COSFloat) iter.next();
        //                    x.setValue(x.floatValue() + translateX);
        //                    y.setValue(y.floatValue() + translateY);
        //                }
        //            }
    }
}

From source file:org.apache.pdfbox.rendering.PageDrawer.java

private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException {
    graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
    setClip();//ww w .  ja va  2  s .com
    PDSoftMask softMask = getGraphicsState().getSoftMask();
    if (softMask != null) {
        AffineTransform imageTransform = new AffineTransform(at);
        imageTransform.scale(1, -1);
        imageTransform.translate(0, -1);
        Paint awtPaint = new TexturePaint(image, new Rectangle2D.Double(imageTransform.getTranslateX(),
                imageTransform.getTranslateY(), imageTransform.getScaleX(), imageTransform.getScaleY()));
        awtPaint = applySoftMaskToPaint(awtPaint, softMask);
        graphics.setPaint(awtPaint);
        Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1);
        graphics.fill(at.createTransformedShape(unitRect));
    } else {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        AffineTransform imageTransform = new AffineTransform(at);
        imageTransform.scale(1.0 / width, -1.0 / height);
        imageTransform.translate(0, -height);
        graphics.drawImage(image, imageTransform, null);
    }
}

From source file:org.geoserver.data.test.MockData.java

void coverageInfo(QName name, File coverageFile, String styleName) throws Exception {
    String coverage = name.getLocalPart();

    File coverageDir = new File(coverages, coverage);
    coverageDir.mkdir();/*ww w. j av a 2  s  .  c  o m*/

    File info = new File(coverageDir, "info.xml");
    info.createNewFile();

    // let's grab the necessary metadata
    AbstractGridFormat format = (AbstractGridFormat) GridFormatFinder.findFormat(coverageFile);
    GridCoverage2DReader reader;
    try {
        reader = (GridCoverage2DReader) format.getReader(coverageFile);
    } catch (Exception e) {
        String message = "Exception while trying to read " + coverageFile.getCanonicalPath() + " with format"
                + format.getName();
        throw new RuntimeException(message, e);
    }

    if (reader == null) {
        throw new RuntimeException(
                "No reader for " + coverageFile.getCanonicalPath() + " with format " + format.getName());
    }
    // basic info
    FileWriter writer = new FileWriter(info);
    writer.write("<coverage format=\"" + coverage + "\">\n");
    writer.write("<name>" + coverage + "</name>\n");
    writer.write("<label>" + coverage + "</label>\n");
    writer.write("<description>" + coverage + " description</description>\n");
    writer.write(
            "<metadataLink about = \"http://www.remotesensing.org:16080/websites/geotiff/geotiff.html\" metadataType = \"other\" />");
    writer.write("<keywords>WCS," + coverage + " </keywords>\n");
    if (styleName == null)
        styleName = "raster";
    writer.write("<styles default=\"" + styleName + "\"/>\n");

    // envelope
    CoordinateReferenceSystem crs = reader.getCoordinateReferenceSystem();
    GeneralEnvelope envelope = reader.getOriginalEnvelope();
    GeneralEnvelope wgs84envelope = CoverageStoreUtils.getWGS84LonLatEnvelope(envelope);
    final String nativeCrsName = CRS.lookupIdentifier(crs, false);
    writer.write("<envelope crs=\"" + crs.toString().replaceAll("\"", "'") + "\" srsName=\"" + nativeCrsName
            + "\">\n");
    writer.write("<pos>" + wgs84envelope.getMinimum(0) + " " + wgs84envelope.getMinimum(1) + "</pos>\n");
    writer.write("<pos>" + wgs84envelope.getMaximum(0) + " " + wgs84envelope.getMaximum(1) + "</pos>\n");
    writer.write("</envelope>\n");

    /**
     * Now reading a fake small GridCoverage just to retrieve meta information:
     * - calculating a new envelope which is 1/20 of the original one
     * - reading the GridCoverage subset
     */

    final ParameterValueGroup readParams = reader.getFormat().getReadParameters();
    final Map parameters = CoverageUtils.getParametersKVP(readParams);
    double[] minCP = envelope.getLowerCorner().getCoordinate();
    double[] maxCP = new double[] { minCP[0] + (envelope.getSpan(0) / 20.0),
            minCP[1] + (envelope.getSpan(1) / 20.0) };
    final GeneralEnvelope subEnvelope = new GeneralEnvelope(minCP, maxCP);
    subEnvelope.setCoordinateReferenceSystem(reader.getCoordinateReferenceSystem());

    parameters.put(AbstractGridFormat.READ_GRIDGEOMETRY2D.getName().toString(),
            new GridGeometry2D(reader.getOriginalGridRange(), subEnvelope));
    GridCoverage2D gc = (GridCoverage2D) reader.read(CoverageUtils.getParameters(readParams, parameters, true));

    // grid geometry
    final GridGeometry geometry = gc.getGridGeometry();
    final int dimensions = geometry.getGridRange().getDimension();
    String lower = "";
    String upper = "";
    for (int i = 0; i < dimensions; i++) {
        lower = lower + geometry.getGridRange().getLow(i) + " ";
        upper = upper + geometry.getGridRange().getHigh(i) + " ";
    }
    writer.write("<grid dimension = \"" + dimensions + "\">\n");
    writer.write("<low>" + lower + "</low>\n");
    writer.write("<high>" + upper + "</high>\n");
    final CoordinateSystem cs = crs.getCoordinateSystem();
    for (int i = 0; i < cs.getDimension(); i++) {
        writer.write("<axisName>" + cs.getAxis(i).getName().getCode() + "</axisName>\n");
    }
    if (geometry.getGridToCRS() instanceof AffineTransform) {
        AffineTransform aTX = (AffineTransform) geometry.getGridToCRS();
        writer.write("<geoTransform>");
        writer.write("<scaleX>" + aTX.getScaleX() + "</scaleX>\n");
        writer.write("<scaleY>" + aTX.getScaleY() + "</scaleY>\n");
        writer.write("<shearX>" + aTX.getShearX() + "</shearX>\n");
        writer.write("<shearY>" + aTX.getShearY() + "</shearY>\n");
        writer.write("<translateX>" + aTX.getTranslateX() + "</translateX>\n");
        writer.write("<translateY>" + aTX.getTranslateY() + "</translateY>\n");
        writer.write("</geoTransform>\n");
    }
    writer.write("</grid>\n");

    // coverage dimensions
    final GridSampleDimension[] sd = gc.getSampleDimensions();
    for (int i = 0; i < sd.length; i++) {
        writer.write("<CoverageDimension>\n");
        writer.write("<name>" + sd[i].getDescription().toString() + "</name>\n");
        writer.write("<interval>\n");
        writer.write("<min>" + sd[i].getMinimumValue() + "</min>\n");
        writer.write("<max>" + sd[i].getMaximumValue() + "</max>\n");
        writer.write("</interval>\n");
        final List<Category> categories = sd[i].getCategories();
        if (categories != null && categories.size() >= 1) {
            writer.write("<nullValues>\n");
            for (Iterator<Category> it = sd[i].getCategories().iterator(); it.hasNext();) {
                Category cat = (Category) it.next();
                if ((cat != null) && cat.getName().toString().equalsIgnoreCase("no data")) {
                    double min = cat.getRange().getMinimum();
                    double max = cat.getRange().getMaximum();
                    writer.write("<value>" + min + "</value>\n");
                    if (min != max)
                        writer.write("<value>" + max + "</value>\n");
                }
            }
            writer.write("</nullValues>\n");
        } else
            writer.write("<nullValues/>\n");
        writer.write("</CoverageDimension>\n");
    }

    // supported crs
    writer.write("<supportedCRSs>\n");
    writer.write("<requestCRSs>" + nativeCrsName + "</requestCRSs>\n");
    writer.write("<responseCRSs>" + nativeCrsName + "</responseCRSs>\n");
    writer.write("</supportedCRSs>\n");

    // supported formats
    writer.write("<supportedFormats nativeFormat = \"" + format.getName() + "\">\n");
    writer.write("<formats>ARCGRID,ARCGRID-GZIP,GEOTIFF,PNG,GIF,TIFF</formats>\n");
    writer.write("</supportedFormats>\n");

    // supported interpolations
    writer.write("<supportedInterpolations default = \"nearest neighbor\">\n");
    writer.write("<interpolationMethods>nearest neighbor</interpolationMethods>\n");
    writer.write("</supportedInterpolations>\n");

    // the end
    writer.write("</coverage>\n");
    writer.flush();
    writer.close();
}

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.
*///from   w  w  w.  j av a2s  . co 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();
            }
        }
    }
}