Example usage for java.awt.geom AffineTransform getScaleX

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

Introduction

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

Prototype

public double getScaleX() 

Source Link

Document

Returns the m00 element of the 3x3 affine transformation matrix.

Usage

From source file:org.apache.fop.render.pdf.PDFImageHandlerSVG.java

/** {@inheritDoc} */
public void handleImage(RenderingContext context, // CSOK: MethodLength
        Image image, Rectangle pos) throws IOException {
    PDFRenderingContext pdfContext = (PDFRenderingContext) context;
    PDFContentGenerator generator = pdfContext.getGenerator();
    ImageXMLDOM imageSVG = (ImageXMLDOM) image;

    FOUserAgent userAgent = context.getUserAgent();
    final float deviceResolution = userAgent.getTargetResolution();
    if (log.isDebugEnabled()) {
        log.debug("Generating SVG at " + deviceResolution + "dpi.");
    }/* w  w  w .  j a  v a2  s .c om*/

    final float uaResolution = userAgent.getSourceResolution();
    SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform());

    GVTBuilder builder = new GVTBuilder();

    //Controls whether text painted by Batik is generated using text or path operations
    boolean strokeText = false;
    //TODO connect with configuration elsewhere.

    BridgeContext ctx = new PDFBridgeContext(ua, (strokeText ? null : pdfContext.getFontInfo()),
            userAgent.getFactory().getImageManager(), userAgent.getImageSessionContext(),
            new AffineTransform());

    //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine)
    //to it.
    Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument());

    GraphicsNode root;
    try {
        root = builder.build(ctx, clonedDoc);
        builder = null;
    } catch (Exception e) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI());
        return;
    }
    // get the 'width' and 'height' attributes of the SVG document
    float w = image.getSize().getWidthMpt();
    float h = image.getSize().getHeightMpt();

    float sx = pos.width / w;
    float sy = pos.height / h;

    //Scaling and translation for the bounding box of the image
    AffineTransform scaling = new AffineTransform(sx, 0, 0, sy, pos.x / 1000f, pos.y / 1000f);
    double sourceScale = UnitConv.IN2PT / uaResolution;
    scaling.scale(sourceScale, sourceScale);

    //Scale for higher resolution on-the-fly images from Batik
    AffineTransform resolutionScaling = new AffineTransform();
    double targetScale = uaResolution / deviceResolution;
    resolutionScaling.scale(targetScale, targetScale);
    resolutionScaling.scale(1.0 / sx, 1.0 / sy);

    //Transformation matrix that establishes the local coordinate system for the SVG graphic
    //in relation to the current coordinate system
    AffineTransform imageTransform = new AffineTransform();
    imageTransform.concatenate(scaling);
    imageTransform.concatenate(resolutionScaling);

    if (log.isTraceEnabled()) {
        log.trace("nat size: " + w + "/" + h);
        log.trace("req size: " + pos.width + "/" + pos.height);
        log.trace("source res: " + uaResolution + ", targetRes: " + deviceResolution + " --> target scaling: "
                + targetScale);
        log.trace(image.getSize());
        log.trace("sx: " + sx + ", sy: " + sy);
        log.trace("scaling: " + scaling);
        log.trace("resolution scaling: " + resolutionScaling);
        log.trace("image transform: " + resolutionScaling);
    }

    /*
     * Clip to the svg area.
     * Note: To have the svg overlay (under) a text area then use
     * an fo:block-container
     */
    if (log.isTraceEnabled()) {
        generator.comment("SVG setup");
    }
    generator.saveGraphicsState();
    if (context.getUserAgent().isAccessibilityEnabled()) {
        MarkedContentInfo mci = pdfContext.getMarkedContentInfo();
        generator.beginMarkedContentSequence(mci.tag, mci.mcid);
    }
    generator.updateColor(Color.black, false, null);
    generator.updateColor(Color.black, true, null);

    if (!scaling.isIdentity()) {
        if (log.isTraceEnabled()) {
            generator.comment("viewbox");
        }
        generator.add(CTMHelper.toPDFString(scaling, false) + " cm\n");
    }

    //SVGSVGElement svg = ((SVGDocument)doc).getRootElement();

    PDFGraphics2D graphics = new PDFGraphics2D(true, pdfContext.getFontInfo(), generator.getDocument(),
            generator.getResourceContext(), pdfContext.getPage().referencePDF(), "", 0);
    graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

    if (!resolutionScaling.isIdentity()) {
        if (log.isTraceEnabled()) {
            generator.comment("resolution scaling for " + uaResolution + " -> " + deviceResolution);
        }
        generator.add(CTMHelper.toPDFString(resolutionScaling, false) + " cm\n");
        graphics.scale(1.0 / resolutionScaling.getScaleX(), 1.0 / resolutionScaling.getScaleY());
    }

    if (log.isTraceEnabled()) {
        generator.comment("SVG start");
    }

    //Save state and update coordinate system for the SVG image
    generator.getState().save();
    generator.getState().concatenate(imageTransform);

    //Now that we have the complete transformation matrix for the image, we can update the
    //transformation matrix for the AElementBridge.
    PDFAElementBridge aBridge = (PDFAElementBridge) ctx.getBridge(SVGDOMImplementation.SVG_NAMESPACE_URI,
            SVGConstants.SVG_A_TAG);
    aBridge.getCurrentTransform().setTransform(generator.getState().getTransform());

    graphics.setPaintingState(generator.getState());
    graphics.setOutputStream(generator.getOutputStream());
    try {
        root.paint(graphics);
        ctx.dispose();
        generator.add(graphics.getString());
    } catch (Exception e) {
        SVGEventProducer eventProducer = SVGEventProducer.Provider
                .get(context.getUserAgent().getEventBroadcaster());
        eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI());
    }
    generator.getState().restore();
    if (context.getUserAgent().isAccessibilityEnabled()) {
        generator.restoreGraphicsStateAccess();
    } else {
        generator.restoreGraphicsState();
    }
    if (log.isTraceEnabled()) {
        generator.comment("SVG end");
    }
}

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

@Override
public void drawImage(PDImage pdImage) throws IOException {
    Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
    AffineTransform at = ctm.createAffineTransform();

    if (!pdImage.getInterpolate()) {
        boolean isScaledUp = pdImage.getWidth() < Math.round(at.getScaleX())
                || pdImage.getHeight() < Math.round(at.getScaleY());

        // if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364
        // only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf
        // stencils are excluded from this rule (see survey.pdf)
        if (isScaledUp || pdImage.isStencil()) {
            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                    RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
        }/* w  w w  .java 2s  .  c  o  m*/
    }

    if (pdImage.isStencil()) {
        // fill the image with paint
        BufferedImage image = pdImage.getStencilImage(getNonStrokingPaint());

        // draw the image
        drawBufferedImage(image, at);
    } else {
        // draw the image
        drawBufferedImage(pdImage.getImage(), at);
    }

    if (!pdImage.getInterpolate()) {
        // JDK 1.7 has a bug where rendering hints are reset by the above call to
        // the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
        setRenderingHints();
    }
}

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

private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException {
    graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
    setClip();//from   w w  w  .  j a va2  s.co m
    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.apache.pdfbox.util.operator.pagedrawer.BeginInlineImage.java

/**
 * process : BI : begin inline image./*ww  w.ja va  2s  . c o m*/
 * @param operator The operator that is being executed.
 * @param arguments List
 * @throws IOException If there is an error displaying the inline image.
 */
public void process(PDFOperator operator, List<COSBase> arguments) throws IOException {
    PageDrawer drawer = (PageDrawer) context;
    PDPage page = drawer.getPage();
    //begin inline image object
    ImageParameters params = operator.getImageParameters();
    PDInlinedImage image = new PDInlinedImage();
    image.setImageParameters(params);
    image.setImageData(operator.getImageData());
    BufferedImage awtImage = image.createImage(context.getColorSpaces());

    if (awtImage == null) {
        log.warn("BeginInlineImage.process(): createImage returned NULL");
        return;
    }
    int imageWidth = awtImage.getWidth();
    int imageHeight = awtImage.getHeight();
    double pageHeight = drawer.getPageSize().getHeight();

    Matrix ctm = drawer.getGraphicsState().getCurrentTransformationMatrix();
    int pageRotation = page.findRotation();

    AffineTransform ctmAT = ctm.createAffineTransform();
    ctmAT.scale(1f / imageWidth, 1f / imageHeight);
    Matrix rotationMatrix = new Matrix();
    rotationMatrix.setFromAffineTransform(ctmAT);
    // calculate the inverse rotation angle
    // scaleX = m00 = cos
    // shearX = m01 = -sin
    // tan = sin/cos
    double angle = Math.atan(ctmAT.getShearX() / ctmAT.getScaleX());
    Matrix translationMatrix = null;
    if (pageRotation == 0 || pageRotation == 180) {
        translationMatrix = Matrix.getTranslatingInstance((float) (Math.sin(angle) * ctm.getXScale()),
                (float) (pageHeight - 2 * ctm.getYPosition() - Math.cos(angle) * ctm.getYScale()));
    } else if (pageRotation == 90 || pageRotation == 270) {
        translationMatrix = Matrix.getTranslatingInstance((float) (Math.sin(angle) * ctm.getYScale()),
                (float) (pageHeight - 2 * ctm.getYPosition()));
    }
    rotationMatrix = rotationMatrix.multiply(translationMatrix);
    rotationMatrix.setValue(0, 1, (-1) * rotationMatrix.getValue(0, 1));
    rotationMatrix.setValue(1, 0, (-1) * rotationMatrix.getValue(1, 0));
    AffineTransform at = new AffineTransform(rotationMatrix.getValue(0, 0), rotationMatrix.getValue(0, 1),
            rotationMatrix.getValue(1, 0), rotationMatrix.getValue(1, 1), rotationMatrix.getValue(2, 0),
            rotationMatrix.getValue(2, 1));
    drawer.drawImage(awtImage, at);
}

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();/*from  w  w  w  .ja v a  2s  .  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.
*//* w  w  w.j ava  2s.c  om*/
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();
            }
        }
    }
}

From source file:org.jcurl.core.base.CurveTransformedTest.java

public void testAffineTransformRotate() {
    final Rock v0 = new RockDouble(1, 1.5, 0.3);
    final double[] d = { v0.getY(), -v0.getX(), v0.getX(), v0.getY(), 0, 0 };
    final AffineTransform at = new AffineTransform(d);
    final double v = v0.distance(0, 0);
    at.scale(1 / v, 1 / v);/*from   ww  w. j a  va2s  . co m*/
    assertEquals(AffineTransform.TYPE_GENERAL_ROTATION, at.getType());
    assertEquals("", 1.0, at.getDeterminant(), 1e-9);
    assertEquals("", 0.8320502943378437, at.getScaleX(), 1e-9);
    assertEquals("", at.getScaleX(), at.getScaleY(), 1e-9);
    assertEquals("", 0.5547001962252291, at.getShearX(), 1e-9);
    assertEquals("", -at.getShearX(), at.getShearY(), 1e-9);
    assertEquals("", 0.0, at.getTranslateX(), 1e-9);
    assertEquals("", 0.0, at.getTranslateY(), 1e-9);
    Point2D p = null;
    p = at.transform(new Point2D.Double(1, 0), null);
    assertEquals("Point2D.Double[0.8320502943378437, -0.5547001962252291]", p.toString());
    assertEquals("", 1.0, p.distanceSq(0, 0), 1e-9);
    p = at.transform(new Point2D.Double(0, 1), null);
    assertEquals("Point2D.Double[0.5547001962252291, 0.8320502943378437]", p.toString());
    assertEquals("", 1.0, p.distanceSq(0, 0), 1e-9);
    p = at.transform(new Point2D.Double(0.75, 1.5), null);
    assertEquals("Point2D.Double[1.4560880150912265, 0.8320502943378438]", p.toString());
    p = at.transform(new Point2D.Double(1.5, 3.0), null);
    assertEquals("Point2D.Double[2.912176030182453, 1.6641005886756877]", p.toString());
}

From source file:org.jcurl.core.base.CurveTransformedTest.java

/**
 * Test the transformation from a Rock Coordinates (rc) System at wc(3,3.5)
 * with positive y axis along wc(2,4.2) into World Coordinates (wc). Uses a
 * Point rc(5,1.3) = wc(8,2.5).//from w ww.j  a v  a2 s  . c o  m
 */
public void testAffineTransformRotateShift() {
    final Point2D p0_wc = new Point2D.Double(3, 3.5);
    final Rock v0_wc = new RockDouble(2, 4.2, 0.3);
    final double v = v0_wc.distance(0, 0);
    final double[] d = { v0_wc.getY(), -v0_wc.getX(), v0_wc.getX(), v0_wc.getY(), 0, 0 };
    final AffineTransform at = new AffineTransform(d);
    at.scale(1 / v, 1 / v);
    assertEquals(AffineTransform.TYPE_GENERAL_ROTATION + AffineTransform.TYPE_UNIFORM_SCALE, at.getType());
    assertEquals(1.0, at.getDeterminant());
    assertEquals(0.9028605188239303, at.getScaleX());
    assertEquals(at.getScaleX(), at.getScaleY());
    assertEquals(0.42993358039234775, at.getShearX());
    assertEquals(-at.getShearX(), at.getShearY());
    assertEquals(0, at.getTranslateX());
    assertEquals(0, at.getTranslateY());
    Point2D p = null;
    p = at.transform(new Point2D.Double(5, 1.3), null);
    assertEquals("Point2D.Double[5.073216248629703, -0.9759492274906292]", p.toString());

    at.preConcatenate(AffineTransform.getTranslateInstance(p0_wc.getX(), p0_wc.getY()));
    assertEquals(AffineTransform.TYPE_GENERAL_ROTATION + AffineTransform.TYPE_TRANSLATION
            + AffineTransform.TYPE_UNIFORM_SCALE, at.getType());
    assertEquals(1.0, at.getDeterminant());
    assertEquals(0.9028605188239303, at.getScaleX());
    assertEquals(at.getScaleX(), at.getScaleY());
    assertEquals(0.42993358039234775, at.getShearX());
    assertEquals(-at.getShearX(), at.getShearY());
    assertEquals(p0_wc.getX(), at.getTranslateX());
    assertEquals(p0_wc.getY(), at.getTranslateY());

    p = at.transform(new Point2D.Double(5, 1.3), null);
    assertEquals("Point2D.Double[8.073216248629702, 2.524050772509371]", p.toString());
}

From source file:org.jcurl.core.base.CurveTransformedTest.java

/**
 * Test the transformation from a Rock Coordinates (rc) System at wc(3,3.5)
 * with positive y axis along wc(2,4.2) into World Coordinates (wc). Uses a
 * Point rc(5,1.3) = wc(8,2.5)./*from   w ww. j  a v a 2 s  . c o  m*/
 * 
 * @see CurveTransformed#createRc2Wc(AffineTransform, Point2D, Point2D)
 */
public void testCreateRc2Wc() {
    final Point2D p0_wc = new Point2D.Double(3, 3.5);
    final Rock v0_wc = new RockDouble(2, 4.2, 0.3);
    final AffineTransform at = CurveTransformed.createRc2Wc(null, p0_wc, v0_wc);
    assertEquals(AffineTransform.TYPE_GENERAL_ROTATION + AffineTransform.TYPE_TRANSLATION, at.getType());
    assertEquals(1.0, at.getDeterminant());
    assertEquals(0.9028605188239303, at.getScaleX());
    assertEquals(at.getScaleX(), at.getScaleY());
    assertEquals(0.42993358039234775, at.getShearX());
    assertEquals(-at.getShearX(), at.getShearY());
    assertEquals(p0_wc.getX(), at.getTranslateX());
    assertEquals(p0_wc.getY(), at.getTranslateY());

    final Point2D rc = new Point2D.Double(5, 1.3);
    final Point2D wc = at.transform(rc, null);
    assertEquals("Point2D.Double[8.073216248629704, 2.524050772509371]", wc.toString());

    // angle in rc:
    double ang = Math.atan2(rc.getY(), rc.getX());
    assertEquals(14.574216198038739, rad2deg(ang));

    // wc rotation:
    ang = Math.atan2(at.getShearY(), at.getScaleY());
    assertEquals(-25.463345061871614, rad2deg(ang));
    final double[] d = new double[6];
    at.getMatrix(d);
    ang = Math.atan2(-d[2], d[3]);
    assertEquals(-25.463345061871614, rad2deg(ang));

    // angle in wc:
    ang = Math.atan2(wc.getY(), wc.getX());
    assertEquals(17.36159358309492, rad2deg(ang));
}

From source file:org.jhotdraw.samples.svg.figures.SVGImage.java

@Override
public void draw(Graphics2D g) {
    AffineTransform t = g.getTransform();
    double scaleX = t.getScaleX();
    if (scaleX == 1.0) {
        g.drawImage(image, null, 0, 0);/*from w ww  .  j  ava2 s. c o  m*/
        return;
    }
    g.scale(1 / scaleX, 1 / scaleX);
    BufferedImage scaledImage = scaledImages.get(scaleX);
    if (scaledImage == null) {
        int w = (int) (image.getWidth() * scaleX);
        int h = (int) (image.getHeight() * scaleX);
        scaledImage = new BufferedImage(w, h, image.getType());
        Graphics2D g2 = scaledImage.createGraphics();
        g2.drawImage(image, 0, 0, w, h, null);
        g2.dispose();
        scaledImages.put((Double) scaleX, scaledImage);
    }
    g.drawImage(scaledImage, null, 0, 0);
    g.setTransform(t);
}