Example usage for java.awt.geom AffineTransform getScaleY

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

Introduction

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

Prototype

public double getScaleY() 

Source Link

Document

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

Usage

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

private void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException {
    graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
    setClip();//  w  w  w. j a va2 s.c  o  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.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   ww w  .  j a va2  s  .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();
            }
        }
    }
}

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);/*w w  w . ja  v a2s  .com*/
    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  ww w.ja va2 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 w w.  j a v  a  2s  . 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.uva.itast.blended.omr.OMRUtils.java

public static void logFrame(PageImage pageImage, PagePoint topleft, PagePoint topright, PagePoint bottomleft,
        PagePoint bottomright, Color color, String label) {
    if (topleft == null || topright == null || bottomleft == null || bottomright == null)
        return;/*from www . j a v a2 s  . c  o  m*/

    Graphics2D g = pageImage.getReportingGraphics();
    AffineTransform t = g.getTransform();
    g.setColor(color);
    g.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1,
            new float[] { (float) (3 / t.getScaleX()), (float) (6 / t.getScaleY()) }, 0));

    // Point framePxUL=pageImage.toPixels(topleft.getX(), topleft.getY());
    // Point framePxUR=pageImage.toPixels(topright.getX(), topright.getY());
    // Point framePxBL=pageImage.toPixels(bottomleft.getX(),
    // bottomleft.getY());
    // Point framePxBR=pageImage.toPixels(bottomright.getX(),
    // bottomright.getY());

    g.drawLine(topleft.getXpx(), topleft.getYpx(), topright.getXpx(), topright.getYpx());
    g.drawLine(topleft.getXpx(), topleft.getYpx(), bottomleft.getXpx(), bottomleft.getYpx());
    g.drawLine(topright.getXpx(), topright.getYpx(), bottomright.getXpx(), bottomright.getYpx());
    g.drawLine(bottomleft.getXpx(), bottomleft.getYpx(), bottomright.getXpx(), bottomright.getYpx());
    if (label != null) {
        g.drawString(label, topleft.getXpx(), topleft.getYpx());
    }
}

From source file:org.uva.itast.blended.omr.scanners.BarcodeScanner.java

/**
 * @param campo/*from  www  . j a v  a2  s . co m*/
 */
public void markBarcode(Field campo) {
    try {
        //get bbox in pixels
        Rectangle rect = pageImage.toPixels(campo.getBBox());
        // expand the area for some tolerance
        Rectangle2D expandedArea = getExpandedArea(campo.getBBox(), (float) BARCODE_AREA_PERCENT);
        Rectangle expandedRect = pageImage.toPixels(expandedArea);

        Graphics2D g = pageImage.getReportingGraphics();
        AffineTransform t = g.getTransform();
        g.setStroke(new BasicStroke(1, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1,
                new float[] { (float) (3 / t.getScaleX()), (float) (6 / t.getScaleY()) }, 0));
        if (lastResult != null)
            g.setColor(Color.BLUE);
        else
            g.setColor(Color.RED);

        g.drawRoundRect(rect.x, rect.y, rect.width, rect.height, 3, 3);
        g.drawRoundRect(expandedRect.x, expandedRect.y, expandedRect.width, expandedRect.height, 3, 3);

        g.setFont(new Font("Arial", Font.BOLD, (int) (12 / t.getScaleX())));
        String message;
        if (lastResult != null)
            message = ((Result) lastResult.getResult()).getBarcodeFormat().toString() + "="
                    + getParsedCode(lastResult);
        else
            message = "UNRECOGNIZED!";
        g.drawString(message, rect.x, rect.y);

    } catch (Exception e) {
        logger.error("Unexpected errr while logging the image:", e);
    }

}

From source file:org.uva.itast.blended.omr.scanners.SolidSquareMarkScanner.java

/**
 * @param pageImage//from w  w  w . j  av  a  2  s. c  o m
 */
public void putEmphasisMarkOnImage(PageImage pageImage, Color color) {

    Graphics2D g = pageImage.getReportingGraphics();
    // int centerColor=imagen.getRGB(maxsimX, maxsimY);
    // g.setXORMode(new Color(centerColor));
    // g.setColor(Color.RED);
    // g.fillOval(maxsimX - markWidth/2, maxsimY - markHeight/2, markWidth,
    // markHeight);
    // g.setPaintMode();
    Dimension2D markDimsPx = pageImage.sizeInPixels(new Size(markWidth, markHeight));
    int markWidth = (int) markDimsPx.getWidth();
    int markHeight = (int) markDimsPx.getHeight();
    g.setColor(color);
    AffineTransform t = g.getTransform();
    g.drawLine(maxsimX, maxsimY - markHeight / 2 - 1, maxsimX,
            maxsimY - markHeight / 2 - (int) (20 / t.getScaleY()));
    Polygon arrowHead = new Polygon();
    arrowHead.addPoint(maxsimX, (int) (maxsimY - markHeight / 2 - 1 / t.getScaleY()));
    arrowHead.addPoint((int) (maxsimX - 6 / t.getScaleX()),
            (int) (maxsimY - markHeight / 2 - 6 / t.getScaleY()));
    arrowHead.addPoint((int) (maxsimX + 6 / t.getScaleX()),
            (int) (maxsimY - markHeight / 2 - 6 / t.getScaleY()));
    g.fillPolygon(arrowHead);

    g.setStroke(new BasicStroke(2, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1,
            new float[] { (float) (3 / t.getScaleX()), (float) (3 / t.getScaleY()) }, 0));
    g.drawRect(maxsimX - markWidth / 2 - 1, maxsimY - markHeight / 2 - 1, markWidth + 1, markHeight + 1);

}

From source file:org.vfny.geoserver.global.xml.XMLConfigWriter.java

protected static void storeCoverage(CoverageInfoDTO cv, File dir) throws ConfigurationException {
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("In method storeCoverage");
    }//from w  ww . j  a  va  2s  . c  om

    File f = WriterUtils.initWriteFile(new File(dir, "info.xml"), false);

    try {
        Writer fw = new OutputStreamWriter(new FileOutputStream(f), getDefaultEncoding());
        WriterHelper cw = new WriterHelper(fw);
        Map m = new HashMap();

        if ((cv.getFormatId() != null) && (cv.getFormatId() != "")) {
            m.put("format", cv.getFormatId());
        }

        cw.openTag("coverage", m);

        if ((cv.getName() != null) && (cv.getName() != "")) {
            cw.textTag("name", cv.getName());
        }

        if ((cv.getLabel() != null) && (cv.getLabel() != "")) {
            cw.textTag("label", cv.getLabel());
        }

        if ((cv.getDescription() != null) && (cv.getDescription() != "")) {
            cw.textTag("description", cv.getDescription());
        }

        if ((cv.getWmsPath() != null) && (cv.getWmsPath() != "")) {
            cw.textTag("wmspath", cv.getWmsPath());
        }

        m = new HashMap();

        if ((cv.getMetadataLink() != null)) {
            m.put("about", cv.getMetadataLink().getAbout());
            m.put("type", cv.getMetadataLink().getType());
            m.put("metadataType", cv.getMetadataLink().getMetadataType());

            cw.openTag("metadataLink", m);
            cw.writeln(cv.getMetadataLink().getContent());
            cw.closeTag("metadataLink");
        }

        if ((cv.getKeywords() != null) && (cv.getKeywords().size() != 0)) {
            String s = "";
            Iterator i = cv.getKeywords().iterator();

            if (i.hasNext()) {
                s = i.next().toString();

                while (i.hasNext()) {
                    s = s + "," + i.next().toString();
                }
            }

            cw.textTag("keywords", s);
        }

        if ((cv.getDefaultStyle() != null) && (cv.getDefaultStyle() != "")) {
            cw.comment("the default style this CoverageInfoDTO can be represented by.\n"
                    + "at least must contain the \"default\" attribute ");
            m = new HashMap();
            m.put("default", cv.getDefaultStyle());

            final ArrayList styles = cv.getStyles();

            if (styles.isEmpty()) {
                cw.attrTag("styles", m);
            } else {
                cw.openTag("styles", m);

                Iterator s_IT = styles.iterator();

                while (s_IT.hasNext())
                    cw.textTag("style", (String) s_IT.next());

                cw.closeTag("styles");
            }
        }

        // //
        // storing the envelope.
        // The native crs wkt is stored as the crs attribute. The user defined srs identifier as
        // the srsName atribute
        // //
        if (cv.getEnvelope() != null) {
            GeneralEnvelope e = cv.getEnvelope();
            m = new HashMap();

            String userDefinedCrsIdentifier = cv.getUserDefinedCrsIdentifier();
            if ((userDefinedCrsIdentifier != null) && (userDefinedCrsIdentifier != "")) {
                m.put("srsName", userDefinedCrsIdentifier);
            }

            String nativeCrsWkt = cv.getNativeCrsWKT();
            m.put("crs", nativeCrsWkt.replaceAll("\"", "'").replaceAll("\r\n", "\n"));

            if (!e.isNull()) {
                cw.comment("crs: native CRS definition, srsName: user defined CRS identifier");
                cw.openTag("envelope", m);
                cw.textTag("pos", e.getLowerCorner().getOrdinate(0) + " " + e.getLowerCorner().getOrdinate(1));
                cw.textTag("pos", e.getUpperCorner().getOrdinate(0) + " " + e.getUpperCorner().getOrdinate(1));
                cw.closeTag("envelope");
            }
        }

        // //
        // AlFa: storing the grid-geometry
        // //
        if (cv.getGrid() != null) {
            GridGeometry g = cv.getGrid();
            MathTransform tx = g.getGridToCRS();

            InternationalString[] dimNames = cv.getDimensionNames();
            m = new HashMap();

            m.put("dimension", new Integer(g.getGridRange().getDimension()));

            String lowers = "";
            String upers = "";

            for (int r = 0; r < g.getGridRange().getDimension(); r++) {
                lowers += (g.getGridRange().getLow(r) + " ");
                upers += (g.getGridRange().getHigh(r) + " ");
            }

            cw.openTag("grid", m);
            cw.textTag("low", lowers);
            cw.textTag("high", upers);

            if (dimNames != null) {
                for (int dn = 0; dn < dimNames.length; dn++)
                    cw.textTag("axisName", dimNames[dn].toString());
            }

            // //
            // AlFa: storing geo-transform
            // //
            if (tx instanceof AffineTransform) {
                AffineTransform aTX = (AffineTransform) tx;
                cw.openTag("geoTransform");
                cw.textTag("scaleX", String.valueOf(aTX.getScaleX()));
                cw.textTag("scaleY", String.valueOf(aTX.getScaleY()));
                cw.textTag("shearX", String.valueOf(aTX.getShearX()));
                cw.textTag("shearY", String.valueOf(aTX.getShearY()));
                cw.textTag("translateX", String.valueOf(aTX.getTranslateX()));
                cw.textTag("translateY", String.valueOf(aTX.getTranslateY()));
                cw.closeTag("geoTransform");
            }

            cw.closeTag("grid");
        }

        if (cv.getDimensions() != null) {
            CoverageDimension[] dims = cv.getDimensions();

            for (int d = 0; d < dims.length; d++) {
                Double[] nulls = dims[d].getNullValues();
                cw.openTag("CoverageDimension");
                cw.textTag("name", dims[d].getName());
                cw.textTag("description", dims[d].getDescription());

                if (dims[d].getRange() != null) {
                    cw.openTag("interval");
                    cw.textTag("min", Double.toString(dims[d].getRange().getMinimum(true)));
                    cw.textTag("max", Double.toString(dims[d].getRange().getMaximum(true)));
                    cw.closeTag("interval");
                } else {
                    cw.openTag("interval");
                    cw.textTag("min", Double.toString(Double.NEGATIVE_INFINITY));
                    cw.textTag("max", Double.toString(Double.POSITIVE_INFINITY));
                    cw.closeTag("interval");
                }

                if (nulls != null) {
                    cw.openTag("nullValues");
                    for (int n = 0; n < nulls.length; n++) {
                        cw.textTag("value", nulls[n].toString());
                    }
                    cw.closeTag("nullValues");
                }
                cw.closeTag("CoverageDimension");
            }
        }

        cw.openTag("supportedCRSs");

        if ((cv.getRequestCRSs() != null) && (cv.getRequestCRSs().size() != 0)) {
            String s = "";
            Iterator i = cv.getRequestCRSs().iterator();

            if (i.hasNext()) {
                s = i.next().toString();

                while (i.hasNext()) {
                    s = s + "," + i.next().toString();
                }
            }

            cw.textTag("requestCRSs", s);
        }

        if ((cv.getResponseCRSs() != null) && (cv.getResponseCRSs().size() != 0)) {
            String s = "";
            Iterator i = cv.getResponseCRSs().iterator();

            if (i.hasNext()) {
                s = i.next().toString();

                while (i.hasNext()) {
                    s = s + "," + i.next().toString();
                }
            }

            cw.textTag("responseCRSs", s);
        }

        cw.closeTag("supportedCRSs");

        m = new HashMap();

        if ((cv.getNativeFormat() != null) && (cv.getNativeFormat() != "")) {
            m.put("nativeFormat", cv.getNativeFormat());
        }

        cw.openTag("supportedFormats", m);

        if ((cv.getSupportedFormats() != null) && (cv.getSupportedFormats().size() != 0)) {
            String s = "";
            Iterator i = cv.getSupportedFormats().iterator();

            if (i.hasNext()) {
                s = i.next().toString();

                while (i.hasNext()) {
                    s = s + "," + i.next().toString();
                }
            }

            cw.textTag("formats", s);
        }

        cw.closeTag("supportedFormats");

        m = new HashMap();

        if ((cv.getDefaultInterpolationMethod() != null) && (cv.getDefaultInterpolationMethod() != "")) {
            m.put("default", cv.getDefaultInterpolationMethod());
        }

        cw.openTag("supportedInterpolations", m);

        if ((cv.getInterpolationMethods() != null) && (cv.getInterpolationMethods().size() != 0)) {
            String s = "";
            Iterator i = cv.getInterpolationMethods().iterator();

            if (i.hasNext()) {
                s = i.next().toString();

                while (i.hasNext()) {
                    s = s + "," + i.next().toString();
                }
            }

            cw.textTag("interpolationMethods", s);
        }

        cw.closeTag("supportedInterpolations");

        // ///////////////////////////////////////////////////////////////////////
        //
        // STORING READ PARAMETERS
        //
        // ///////////////////////////////////////////////////////////////////////
        if ((cv.getParameters() != null) && (cv.getParameters().size() != 0)) {
            cw.openTag("parameters");
            final Iterator i = cv.getParameters().keySet().iterator();
            final HashMap temp = new HashMap();

            while (i.hasNext()) {
                String key = (String) i.next();
                if (cv.getParameters().get(key) != null) {
                    temp.put("name", key);
                    temp.put("value", cv.getParameters().get(key).toString().replaceAll("\"", "'"));
                }
                cw.attrTag("parameter", temp);
            }

            cw.closeTag("parameters");
        }

        cw.closeTag("coverage");
        fw.close();
    } catch (IOException e) {
        throw new ConfigurationException(e);
    }
}