Example usage for java.awt RenderingHints RenderingHints

List of usage examples for java.awt RenderingHints RenderingHints

Introduction

In this page you can find the example usage for java.awt RenderingHints RenderingHints.

Prototype

public RenderingHints(Key key, Object value) 

Source Link

Document

Constructs a new object with the specified key/value pair.

Usage

From source file:lucee.runtime.img.Image.java

public void shear(float shear, ShearDir direction, Object interpolation) throws ExpressionException {
    ParameterBlock params = new ParameterBlock();
    params.addSource(image());/*  w w w  . ja v  a2 s  .c  om*/
    params.add(shear);
    params.add(direction);
    params.add(0.0F);
    params.add(0.0F);
    RenderingHints hints = null;

    if (interpolation == RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR)
        params.add(Interpolation.getInstance(0));
    else if (interpolation == RenderingHints.VALUE_INTERPOLATION_BILINEAR) {
        params.add(Interpolation.getInstance(1));
        BorderExtender extender = BorderExtender.createInstance(1);
        hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
    } else if (interpolation == RenderingHints.VALUE_INTERPOLATION_BICUBIC) {
        params.add(Interpolation.getInstance(2));
        BorderExtender extender = BorderExtender.createInstance(1);
        hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
    }
    // TODO
    Color bg = getGraphics().getBackground();
    params.add(new double[] { bg.getRed(), bg.getGreen(), bg.getBlue() });
    image(JAI.create("shear", params, hints).getAsBufferedImage());
}

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

public RasterManager(final ImageMosaicReader parentReader, MosaicConfigurationBean configuration)
        throws IOException {

    Utilities.ensureNonNull("ImageMosaicReader", parentReader);

    this.parentReader = parentReader;
    this.expandMe = parentReader.expandMe;
    boolean checkAuxiliaryMetadata = configuration.isCheckAuxiliaryMetadata();
    this.heterogeneousGranules = configuration.getCatalogConfigurationBean().isHeterogeneous();
    this.configuration = configuration;
    hints = parentReader.getHints();/*  w  w w  . j  av  a 2  s .c o m*/
    if (configuration != null && configuration.getAuxiliaryFilePath() != null) {
        hints.add(new RenderingHints(Utils.AUXILIARY_FILES_PATH, configuration.getAuxiliaryFilePath()));
    }
    if (checkAuxiliaryMetadata) {
        hints.add(new RenderingHints(Utils.CHECK_AUXILIARY_METADATA, checkAuxiliaryMetadata));
    }

    // take ownership of the index : TODO: REMOVE THAT ONCE DEALING WITH MORE CATALOGS/RASTERMANAGERS
    // granuleCatalog = new HintedGranuleCatalog(parentReader.granuleCatalog, hints);
    granuleCatalog = parentReader.granuleCatalog;
    this.coverageFactory = parentReader.getGridCoverageFactory();
    this.coverageIdentifier = configuration != null ? configuration.getName() : ImageMosaicReader.UNSPECIFIED;
    this.pathType = configuration.getCatalogConfigurationBean().isAbsolutePath() ? PathType.ABSOLUTE
            : PathType.RELATIVE;

    extractOverviewPolicy();
    extractDecimationPolicy();

    // load defaultSM and defaultCM by using the sample_image if it was provided
    loadSampleImage(configuration);

    if (configuration != null) {
        CatalogConfigurationBean catalogBean = configuration.getCatalogConfigurationBean();
        typeName = catalogBean != null ? catalogBean.getTypeName() : null;
        initDomains(configuration);
        if (defaultSM == null) {
            defaultSM = configuration.getSampleModel();
        }

        if (defaultCM == null) {
            defaultCM = configuration.getColorModel();
        }

        if (defaultSM != null && defaultCM != null && defaultImageLayout == null) {
            defaultImageLayout = new ImageLayout().setColorModel(defaultCM).setSampleModel(defaultSM);
        }

        levels = configuration.getLevels();
        final double[] highRes = levels[0];
        final int numOverviews = configuration.getLevelsNum() - 1;
        double[][] overviews = null;
        if (numOverviews > 0) {
            overviews = new double[numOverviews][2];
            for (int i = 0; i < numOverviews; i++) {
                overviews[i][0] = levels[i + 1][0];
                overviews[i][1] = levels[i + 1][1];
            }
        }
        overviewsController = new OverviewsController(highRes, numOverviews, overviews);
        imposedEnvelope = configuration.getEnvelope();
    }
}

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 a  va 2 s.  c  o  m
public GranuleLoadingResult loadRaster(final ImageReadParam imageReadParameters, final int index,
        final ReferencedEnvelope cropBBox, final MathTransform2D mosaicWorldToGrid,
        final RasterLayerRequest request, final Hints hints) throws IOException {

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

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

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

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

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

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

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

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

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

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

            }
            return null;

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

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

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

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

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

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

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

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

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

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

        // adjust roi
        if (useFootprint) {

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

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

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

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

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

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

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

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

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

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

/**
 * This method loads the granules which overlap the requested
 * {@link GeneralEnvelope} using the provided values for alpha and input
 * ROI.//  ww w.ja  v  a  2 s .  co  m
 * @return
 * @throws DataSourceException
 */
private RenderedImage prepareResponse() throws DataSourceException {

    try {

        //
        // prepare the params for executing a mosaic operation.
        //
        // It might important to set the mosaic type to blend otherwise
        // sometimes strange results jump in.

        // select the relevant overview, notice that at this time we have
        // relaxed a bit the requirement to have the same exact resolution
        // for all the overviews, but still we do not allow for reading the
        // various grid to world transform directly from the input files,
        // therefore we are assuming that each granuleDescriptor has a scale and
        // translate only grid to world that can be deduced from its base
        // level dimension and envelope. The grid to world transforms for
        // the other levels can be computed accordingly knowing the scale
        // factors.
        if (request.getRequestedBBox() != null && request.getRequestedRasterArea() != null
                && !request.isHeterogeneousGranules())
            imageChoice = ReadParamsController.setReadParams(request.getRequestedResolution(),
                    request.getOverviewPolicy(), request.getDecimationPolicy(), baseReadParameters,
                    request.rasterManager, request.rasterManager.overviewsController); // use general overviews controller
        else
            imageChoice = 0;
        assert imageChoice >= 0;
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine(new StringBuffer("Loading level ").append(imageChoice)
                    .append(" with subsampling factors ").append(baseReadParameters.getSourceXSubsampling())
                    .append(" ").append(baseReadParameters.getSourceYSubsampling()).toString());

        // ok we got something to return, let's load records from the index
        final BoundingBox cropBBOX = request.getCropBBox();
        if (cropBBOX != null)
            mosaicBBox = ReferencedEnvelope.reference(cropBBOX);
        else
            mosaicBBox = new ReferencedEnvelope(coverageEnvelope);

        //compute final world to grid
        // base grid to world for the center of pixels
        final AffineTransform g2w;
        final OverviewLevel baseLevel = rasterManager.overviewsController.resolutionsLevels.get(0);
        final OverviewLevel selectedLevel = rasterManager.overviewsController.resolutionsLevels
                .get(imageChoice);
        final double resX = baseLevel.resolutionX;
        final double resY = baseLevel.resolutionY;
        final double[] requestRes = request.getRequestedResolution();

        g2w = new AffineTransform((AffineTransform) baseGridToWorld);
        g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if ((requestRes[0] < resX || requestRes[1] < resY)) {
            // Using the best available resolution
            oversampledRequest = true;
        } else {

            // SG going back to working on a per level basis to do the composition
            // g2w = new AffineTransform(request.getRequestedGridToWorld());
            g2w.concatenate(
                    AffineTransform.getScaleInstance(selectedLevel.scaleFactor, selectedLevel.scaleFactor));
            g2w.concatenate(AffineTransform.getScaleInstance(baseReadParameters.getSourceXSubsampling(),
                    baseReadParameters.getSourceYSubsampling()));
        }

        // move it to the corner
        finalGridToWorldCorner = new AffineTransform2D(g2w);
        finalWorldToGridCorner = finalGridToWorldCorner.inverse();// compute raster bounds
        final GeneralEnvelope tempRasterBounds = CRS.transform(finalWorldToGridCorner, mosaicBBox);
        rasterBounds = tempRasterBounds.toRectangle2D().getBounds();

        //          SG using the above may lead to problems since the reason is that  may be a little (1 px) bigger
        //          than what we need. The code below is a bit better since it uses a proper logic (see GridEnvelope
        //          Javadoc)
        //         rasterBounds = new GridEnvelope2D(new Envelope2D(tempRasterBounds), PixelInCell.CELL_CORNER);
        if (rasterBounds.width == 0)
            rasterBounds.width++;
        if (rasterBounds.height == 0)
            rasterBounds.height++;
        if (oversampledRequest)
            rasterBounds.grow(2, 2);

        // make sure we do not go beyond the raster dimensions for this layer
        final GeneralEnvelope levelRasterArea_ = CRS.transform(finalWorldToGridCorner,
                rasterManager.spatialDomainManager.coverageBBox);
        final GridEnvelope2D levelRasterArea = new GridEnvelope2D(new Envelope2D(levelRasterArea_),
                PixelInCell.CELL_CORNER);
        XRectangle2D.intersect(levelRasterArea, rasterBounds, rasterBounds);

        // create the index visitor and visit the feature
        final MosaicBuilder visitor = new MosaicBuilder(request);
        final List times = request.getRequestedTimes();
        final List elevations = request.getElevation();
        final Map<String, List> additionalDomains = request.getRequestedAdditionalDomains();
        final Filter filter = request.getFilter();
        final boolean hasTime = (times != null && times.size() > 0);
        final boolean hasElevation = (elevations != null && elevations.size() > 0);
        final boolean hasAdditionalDomains = additionalDomains.size() > 0;
        final boolean hasFilter = filter != null && !Filter.INCLUDE.equals(filter);

        // create query
        final SimpleFeatureType type = rasterManager.granuleCatalog.getType();
        Query query = null;
        Filter bbox = null;
        if (type != null) {
            query = new Query(rasterManager.granuleCatalog.getType().getTypeName());
            bbox = FeatureUtilities.DEFAULT_FILTER_FACTORY.bbox(
                    FeatureUtilities.DEFAULT_FILTER_FACTORY
                            .property(rasterManager.granuleCatalog.getType().getGeometryDescriptor().getName()),
                    mosaicBBox);
            query.setFilter(bbox);
        } else {
            throw new IllegalStateException("GranuleCatalog feature type was null!!!");
        }

        // prepare eventual filter for filtering granules
        // handle elevation indexing first since we then combine this with the max in case we are asking for current in time
        if (hasElevation) {

            final Filter elevationF = rasterManager.parent.elevationDomainManager
                    .createFilter(ImageMosaicReader.ELEVATION_DOMAIN, elevations);
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), elevationF));
        }

        // handle generic filter since we then combine this with the max in case we are asking for current in time
        if (hasFilter) {
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), filter));
        }

        // fuse time query with the bbox query
        if (hasTime) {
            final Filter timeFilter = this.rasterManager.parent.timeDomainManager
                    .createFilter(ImageMosaicReader.TIME_DOMAIN, times);
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), timeFilter));
        }

        if (hasAdditionalDomains) {
            final List<Filter> additionalFilter = new ArrayList<Filter>();
            for (Entry<String, List> entry : additionalDomains.entrySet()) {

                // build a filter for each dimension
                final String domainName = entry.getKey() + DomainDescriptor.DOMAIN_SUFFIX;
                additionalFilter.add(
                        rasterManager.parent.domainsManager.createFilter(domainName, (List) entry.getValue()));

            }
            // merge with existing ones
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(),
                    FeatureUtilities.DEFAULT_FILTER_FACTORY.and(additionalFilter)));
        }

        //
        // handle secondary query parameters
        //

        // max number of elements
        if (request.getMaximumNumberOfGranules() > 0) {
            query.setMaxFeatures(request.getMaximumNumberOfGranules());
        }

        // sort by clause
        final String sortByClause = request.getSortClause();
        if (sortByClause != null && sortByClause.length() > 0) {
            final String[] elements = sortByClause.split(",");
            if (elements != null && elements.length > 0) {
                final List<SortBy> clauses = new ArrayList<SortBy>(elements.length);
                for (String element : elements) {
                    // check
                    if (element == null || element.length() <= 0) {
                        continue;// next, please!
                    }
                    try {
                        // which clause?
                        // ASCENDING
                        element = element.trim();
                        if (element.endsWith(Utils.ASCENDING_ORDER_IDENTIFIER)) {
                            String attribute = element.substring(0, element.length() - 2);
                            clauses.add(
                                    new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),
                                            SortOrder.ASCENDING));
                        } else
                        // DESCENDING
                        if (element.contains(Utils.DESCENDING_ORDER_IDENTIFIER)) {
                            String attribute = element.substring(0, element.length() - 2);
                            clauses.add(
                                    new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),
                                            SortOrder.DESCENDING));
                        }
                        //                        if(element.startsWith(Utils.ASCENDING_ORDER_IDENTIFIER)){
                        //                           String attribute=element.substring(Utils.ASCENDING_ORDER_IDENTIFIER.length()+1);
                        //                           attribute=attribute.substring(0, attribute.length()-1);
                        //                           clauses.add(new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),SortOrder.ASCENDING));
                        //                        } else 
                        //                           // DESCENDING
                        //                           if(element.startsWith(Utils.DESCENDING_ORDER_IDENTIFIER)){
                        //                               String attribute=element.substring(Utils.DESCENDING_ORDER_IDENTIFIER.length()+1);
                        //                               attribute=attribute.substring(0, attribute.length()-1);
                        //                               clauses.add(new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),SortOrder.DESCENDING));
                        //                        } else {
                        else {
                            if (LOGGER.isLoggable(Level.FINE)) {
                                LOGGER.fine("Ignoring sort clause :" + element);
                            }
                        }
                    } catch (Exception e) {
                        if (LOGGER.isLoggable(Level.INFO)) {
                            LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
                        }
                    }
                }

                // assign to query if sorting is supported!
                final SortBy[] sb = clauses.toArray(new SortBy[] {});
                if (rasterManager.granuleCatalog.getQueryCapabilities().supportsSorting(sb)) {
                    query.setSortBy(sb);
                }
            }
        }

        // collect granules
        rasterManager.getGranules(query, visitor);

        // get those granules
        visitor.produce();

        //
        // Did we actually load anything?? Notice that it might happen that
        // either we have holes inside the definition area for the mosaic
        // or we had some problem with missing tiles, therefore it might
        // happen that for some bboxes we don't have anything to load.
        //
        RenderedImage returnValue = null;
        if (visitor.granulesNumber >= 1) {

            //
            // Create the mosaic image by doing a crop if necessary and also
            // managing the transparent color if applicable. Be aware that
            // management of the transparent color involves removing
            // transparency information from the input images.
            //          
            returnValue = buildMosaic(visitor);
            if (returnValue != null) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine("Loaded bbox " + mosaicBBox.toString() + " while crop bbox "
                            + request.getCropBBox().toString());
                return returnValue;
            }

        }

        // Redo the query without filter to check whether we got no granules due
        // to a filter. In that case we need to return null
        if (hasTime || hasElevation || hasFilter || hasAdditionalDomains) {
            query.setFilter(bbox);
            rasterManager.getGranules(query, visitor);
            // get those granules
            visitor.produce();
            if (visitor.granulesNumber >= 1) {
                // It means the previous lack of granule was due to a filter excluding all the results. Then we return null
                return null;
            }
        }

        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("Creating constant image for area with no data");

        // if we get here that means that we do not have anything to load
        // but still we are inside the definition area for the mosaic,
        // therefore we create a fake coverage using the background values,
        // if provided (defaulting to 0), as well as the compute raster
        // bounds, envelope and grid to world.

        final Number[] values = ImageUtilities.getBackgroundValues(rasterManager.defaultSM, backgroundValues);
        // create a constant image with a proper layout
        RenderedImage finalImage = ConstantDescriptor.create(Float.valueOf(rasterBounds.width),
                Float.valueOf(rasterBounds.height), values, null);
        if (rasterBounds.x != 0 || rasterBounds.y != 0) {
            finalImage = TranslateDescriptor.create(finalImage, Float.valueOf(rasterBounds.x),
                    Float.valueOf(rasterBounds.y), Interpolation.getInstance(Interpolation.INTERP_NEAREST),
                    null);
        }
        if (rasterManager.defaultCM != null) {
            final ImageLayout2 il = new ImageLayout2();
            il.setColorModel(rasterManager.defaultCM);
            Dimension tileSize = request.getTileDimensions();
            if (tileSize == null) {
                tileSize = JAI.getDefaultTileSize();
            }
            il.setSampleModel(
                    rasterManager.defaultCM.createCompatibleSampleModel(tileSize.width, tileSize.height));
            il.setTileGridXOffset(0).setTileGridYOffset(0).setTileWidth((int) tileSize.getWidth())
                    .setTileHeight((int) tileSize.getHeight());
            return FormatDescriptor.create(finalImage, Integer.valueOf(il.getSampleModel(null).getDataType()),
                    new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il));
        }
        return finalImage;

    } catch (Exception e) {
        throw new DataSourceException("Unable to create this mosaic", e);
    }
}

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

/**
 * Once we reach this method it means that we have loaded all the images
 * which were intersecting the requested envelope. Next step is to create
 * the final mosaic image and cropping it to the exact requested envelope.
 * @param visitor // ww  w .jav  a 2 s  .com
 * 
 * @return A {@link RenderedImage}}.
 */
private RenderedImage buildMosaic(final MosaicBuilder visitor) throws IOException {

    // build final layout and use it for cropping purposes
    final ImageLayout layout = new ImageLayout(rasterBounds.x, rasterBounds.y, rasterBounds.width,
            rasterBounds.height);

    //prepare hints
    final Dimension tileDimensions = request.getTileDimensions();
    if (tileDimensions != null) {
        layout.setTileHeight(tileDimensions.width).setTileWidth(tileDimensions.height);
    }
    final RenderingHints localHints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
    if (hints != null && !hints.isEmpty()) {
        if (hints.containsKey(JAI.KEY_TILE_CACHE)) {
            final Object tc = hints.get(JAI.KEY_TILE_CACHE);
            if (tc != null && tc instanceof TileCache)
                localHints.add(new RenderingHints(JAI.KEY_TILE_CACHE, (TileCache) tc));
        }
        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;
            }
        }
        if (addBorderExtender) {
            localHints.add(ImageUtilities.BORDER_EXTENDER_HINTS);
        }
        if (hints.containsKey(JAI.KEY_TILE_SCHEDULER)) {
            final Object ts = hints.get(JAI.KEY_TILE_SCHEDULER);
            if (ts != null && ts instanceof TileScheduler)
                localHints.add(new RenderingHints(JAI.KEY_TILE_SCHEDULER, (TileScheduler) ts));
        }
    }

    //
    // SPECIAL CASE
    // 1 single tile, we try not do a mosaic.
    final ROI[] sourceRoi = visitor.sourceRoi;
    if (visitor.granulesNumber == 1 && Utils.OPTIMIZE_CROP) {
        // the roi is exactly equal to the 
        final ROI roi = visitor.rois.get(0);
        Rectangle bounds = Utils.toRectangle(roi.getAsShape());
        if (bounds != null) {
            RenderedImage image = visitor.getSourcesAsArray()[0];
            Rectangle imageBounds = PlanarImage.wrapRenderedImage(image).getBounds();
            if (imageBounds.equals(bounds)) {

                // do we need to crop? (image is bigger than requested?)
                if (!rasterBounds.contains(imageBounds)) {
                    // we have to crop
                    XRectangle2D.intersect(imageBounds, rasterBounds, imageBounds);

                    if (imageBounds.isEmpty()) {
                        // return back a constant image
                        return null;
                    }
                    // crop
                    ImageWorker iw = new ImageWorker(image);
                    iw.setRenderingHints(localHints);
                    iw.crop(imageBounds.x, imageBounds.y, imageBounds.width, imageBounds.height);

                    image = iw.getRenderedImage();
                    imageBounds = PlanarImage.wrapRenderedImage(image).getBounds();
                }

                // and, do we need to add a border around the image?
                if (!imageBounds.contains(rasterBounds)) {
                    image = MosaicDescriptor.create(new RenderedImage[] { image },
                            request.isBlend() ? MosaicDescriptor.MOSAIC_TYPE_BLEND
                                    : MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
                            (alphaIn || visitor.doInputTransparency) ? visitor.alphaChannels : null, sourceRoi,
                            visitor.sourceThreshold, backgroundValues, localHints);
                }

                return image;
            }
        }
    }

    // 
    // Final Merge
    // 
    // I can even do a stacking merge or a flat merge
    final RenderedImage mosaic = request.getMergeBehavior().process(visitor.getSourcesAsArray(),
            backgroundValues, visitor.sourceThreshold,
            (alphaIn || visitor.doInputTransparency) ? visitor.alphaChannels : null, sourceRoi,
            request.isBlend() ? MosaicDescriptor.MOSAIC_TYPE_BLEND : MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
            localHints);

    if (setRoiProperty) {

        //Adding globalRoi to the output
        RenderedOp rop = (RenderedOp) mosaic;
        ROI globalRoi = null;
        ROI[] rois = sourceRoi;
        for (int i = 0; i < rois.length; i++) {
            if (globalRoi == null) {
                globalRoi = new ROIGeometry(((ROIGeometry) rois[i]).getAsGeometry());
            } else {
                globalRoi = globalRoi.add(rois[i]);
            }
        }
        rop.setProperty("ROI", globalRoi);
    }

    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine("Mosaic created ");

    // create the coverage
    return mosaic;

}

From source file:org.geoserver.catalog.ResourcePool.java

/**
 * Returns a coverage reader, caching the result.
 *  //ww w .java2 s. c  o  m
 * @param info The coverage metadata.
 * @param hints Hints to use when loading the coverage, may be <code>null</code>.
 * 
 * @throws IOException Any errors that occur loading the reader.
 */
@SuppressWarnings("deprecation")
public GridCoverageReader getGridCoverageReader(CoverageStoreInfo info, String coverageName, Hints hints)
        throws IOException {

    final AbstractGridFormat gridFormat = info.getFormat();
    if (gridFormat == null) {
        throw new IOException("Could not find the raster plugin for format " + info.getType());
    }

    // look into the cache
    GridCoverageReader reader = null;
    Object key;
    if (hints != null && info.getId() != null) {
        // expand the hints if necessary
        final String formatName = gridFormat.getName();
        if (formatName.equalsIgnoreCase(IMAGE_MOSAIC) || formatName.equalsIgnoreCase(IMAGE_PYRAMID)) {
            if (coverageExecutor != null) {
                if (hints != null) {
                    // do not modify the caller hints
                    hints = new Hints(hints);
                    hints.add(new RenderingHints(Hints.EXECUTOR_SERVICE, coverageExecutor));
                } else {
                    hints = new Hints(new RenderingHints(Hints.EXECUTOR_SERVICE, coverageExecutor));
                }
            }
        }

        key = new CoverageHintReaderKey(info.getId(), hints);
        reader = (GridCoverage2DReader) hintCoverageReaderCache.get(key);
    } else {
        key = info.getId();
        if (key != null) {
            reader = (GridCoverageReader) coverageReaderCache.get(key);
        }
    }

    // if not found in cache, create it
    if (reader == null) {
        synchronized (hints != null ? hintCoverageReaderCache : coverageReaderCache) {
            if (key != null) {
                if (hints != null) {
                    reader = (GridCoverageReader) hintCoverageReaderCache.get(key);
                } else {
                    reader = (GridCoverageReader) coverageReaderCache.get(key);
                }
            }
            if (reader == null) {
                /////////////////////////////////////////////////////////
                //
                // Getting coverage reader using the format and the real path.
                //
                // /////////////////////////////////////////////////////////
                final String url = info.getURL();
                final File obj = GeoserverDataDirectory.findDataFile(url);
                // In case no File is returned, provide the original String url
                final Object input = obj != null ? obj : url;

                // readers might change the provided hints, pass down a defensive copy
                reader = gridFormat.getReader(input, new Hints(hints));
                if (reader == null) {
                    throw new IOException("Failed to create reader from " + url + " and hints " + hints);
                }
                if (key != null) {
                    if (hints != null) {
                        hintCoverageReaderCache.put((CoverageHintReaderKey) key, reader);
                    } else {
                        coverageReaderCache.put((String) key, reader);
                    }
                }
            }
        }
    }

    // wrap it if we are dealing with a multi-coverage reader
    if (coverageName != null) {
        // force the result to work against a single coverage, so that the OGC service portion of
        // GeoServer does not need to be updated to the multicoverage stuff
        // (we might want to introduce a hint later for code that really wants to get the
        // multi-coverage reader)
        return SingleGridCoverage2DReader.wrap((GridCoverage2DReader) reader, coverageName);
    } else {
        return (GridCoverage2DReader) reader;
    }
}

From source file:lucee.runtime.img.Image.java

public void rotate(float x, float y, float angle, int interpolation) throws ExpressionException {
    if (x == -1)//from w w w  .  jav  a  2s  .  c om
        x = (float) getWidth() / 2;
    if (y == -1)
        y = (float) getHeight() / 2;

    angle = (float) Math.toRadians(angle);
    ColorModel cmSource = image().getColorModel();

    if (cmSource instanceof IndexColorModel && cmSource.hasAlpha() && !cmSource.isAlphaPremultiplied()) {
        image(PaletteToARGB(image()));
        cmSource = image().getColorModel();
    }

    BufferedImage alpha = null;
    if (cmSource.hasAlpha() && !cmSource.isAlphaPremultiplied()) {
        alpha = getAlpha(image());
        image(removeAlpha(image()));
    }

    Interpolation interp = Interpolation.getInstance(0);
    if (INTERPOLATION_BICUBIC == interpolation)
        interp = Interpolation.getInstance(1);
    else if (INTERPOLATION_BILINEAR == interpolation)
        interp = Interpolation.getInstance(2);

    if (alpha != null) {
        ParameterBlock params = new ParameterBlock();
        params.addSource(alpha);
        params.add(x);
        params.add(y);
        params.add(angle);
        params.add(interp);
        params.add(new double[] { 0.0 });
        RenderingHints hints = new RenderingHints(RenderingHints.KEY_INTERPOLATION,
                (RenderingHints.VALUE_INTERPOLATION_BICUBIC));
        hints.add(new RenderingHints(JAI.KEY_BORDER_EXTENDER,
                new BorderExtenderConstant(new double[] { 255.0 })));
        hints.add(new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.TRUE));
        alpha = JAI.create("rotate", params, hints).getAsBufferedImage();
    }

    ParameterBlock params = new ParameterBlock();
    params.addSource(image());
    params.add(x);
    params.add(y);
    params.add(angle);
    params.add(interp);
    params.add(new double[] { 0.0 });
    BorderExtender extender = new BorderExtenderConstant(new double[] { 0.0 });
    RenderingHints hints = new RenderingHints(JAI.KEY_BORDER_EXTENDER, extender);
    hints.add(new RenderingHints(JAI.KEY_REPLACE_INDEX_COLOR_MODEL, Boolean.TRUE));
    image(JAI.create("rotate", params, hints).getAsBufferedImage());
    if (alpha != null)
        image(addAlpha(image(), alpha, 0, 0));
}

From source file:it.geosolutions.geobatch.destination.vulnerability.VulnerabilityComputation.java

/**
 * Method used for merging the input Rasters into a 2 images, one for human targets and the other for not human targets
 * //from   ww  w  .java  2  s.  c  om
 * @param humanTargets
 * @param notHumanTargets
 * @param bandPerTargetH
 * @param bandPerTargetNH
 * @throws IOException
 * @throws java.awt.geom.NoninvertibleTransformException
 * @throws TransformException
 * @throws MismatchedDimensionException
 */
public RenderedImage[] rasterCalculation(Map<Integer, TargetInfo> bandPerTargetH,
        Map<Integer, TargetInfo> bandPerTargetNH) throws IOException,
        java.awt.geom.NoninvertibleTransformException, MismatchedDimensionException, TransformException {
    // Initialization of the images
    RenderedImage humanTargets = null;
    RenderedImage notHumanTargets = null;
    String basePath = System.getProperty(RASTER_PATH_PROP, "");
    if (!basePath.equals("")) {
        basePath = basePath + File.separator + codicePartner;
    }
    // Read of the resources
    Map vulnerabilityConf = (Map) readResourceFromXML("/vulnerability.xml");
    // Vulnerability engine used for extracting the Targets
    VulnerabilityStatsEngine vsengine = new VulnerabilityStatsEngine(basePath, vulnerabilityConf, dataStore,
            DISTANCE_TYPE_NAME, pixelArea);
    // Target Map
    Map<String, TargetInfo> targetInfo = vsengine.getTargetInfo();

    /*
     * Creation of 2 images: one for the HUMAN TARGETS and the other for NOT HUMAN TARGETS
     */
    // List of Human Targets
    List<RenderedImage> humanList = new ArrayList<RenderedImage>();

    // List of Not Human Targets
    List<RenderedImage> notHumanList = new ArrayList<RenderedImage>();

    // Counters indicating which band is associated to the TargetInfo and
    // Image
    int humanBandCounter = 0;
    int notHumanBandCounter = 0;

    // Iterator on all the targets
    Iterator<String> rasterIter = targetInfo.keySet().iterator();

    // Initializations of the parameters for merging the input rasters
    Envelope2D globalBBOXHuman = null;
    Envelope2D globalBBOXNotHuman = null;
    List<AffineTransform> tfHuman = new ArrayList<AffineTransform>();
    List<AffineTransform> tfNotHuman = new ArrayList<AffineTransform>();
    AffineTransform g2WHuman = null;
    AffineTransform g2WNotHuman = null;
    // Cycle on all the rasters
    while (rasterIter.hasNext()) {
        // save the ID of this target
        String targetID = rasterIter.next();

        // Load the target manager, init its status and check if the actual
        // distance is a valid distance for it
        TargetInfo info = targetInfo.get(targetID);

        // Getting of the transformation parameters
        GridGeometry2D gg2D = info.getGG2D();
        Envelope2D envelope = gg2D.getEnvelope2D();
        AffineTransform w2g = (AffineTransform) gg2D.getCRSToGrid2D(PixelOrientation.UPPER_LEFT);
        // getting information about current Target
        TargetManager manager = info.getManager();

        // Image associated to the current target
        RenderedImage newImage = info.getRaster();
        // Image data type
        int imgDataType = newImage.getSampleModel().getDataType();
        // Check if the image really exists
        if (newImage != null) {
            // If the target is human
            if (manager.isHumanTarget()) {
                // Other check for ensuring the target is correct
                if (imgDataType != DataBuffer.TYPE_FLOAT) {
                    System.out.println("Wrong data type");
                }

                // perform union
                if (globalBBOXHuman == null) {
                    globalBBOXHuman = new Envelope2D(envelope);
                } else {
                    globalBBOXHuman.include(envelope);
                }
                // Selection of the first g2w transform as the global one
                if (g2WHuman == null) {
                    g2WHuman = (AffineTransform) gg2D.getGridToCRS2D(PixelOrientation.UPPER_LEFT);
                }

                // Creation of the transformation from destination Raster space to source Raster space
                AffineTransform temp = new AffineTransform(w2g);
                temp.concatenate(g2WHuman);
                tfHuman.add(temp);

                // Addition of the TargetInfo of this target
                bandPerTargetH.put(humanBandCounter, info);
                // Update of the bandCounter
                humanBandCounter++;
                // Addition of the image to the associated list
                humanList.add(newImage);

            } else {
                // Other check for ensuring the target is correct
                if (imgDataType != DataBuffer.TYPE_BYTE) {
                    System.out.println("Wrong data type");
                }

                // perform union
                if (globalBBOXNotHuman == null) {
                    globalBBOXNotHuman = envelope;
                } else {
                    globalBBOXNotHuman.include(envelope);
                }
                // Selection of the first g2w transform as the global one
                if (g2WNotHuman == null) {
                    g2WNotHuman = (AffineTransform) gg2D.getGridToCRS2D(PixelOrientation.UPPER_LEFT);
                }
                // Creation of the transformation from destination Raster space to source Raster space
                AffineTransform temp = new AffineTransform(w2g);
                temp.concatenate(g2WNotHuman);
                tfNotHuman.add(temp);

                // Addition of the TargetInfo of this target
                bandPerTargetNH.put(notHumanBandCounter, info);
                // Update of the bandCounter
                notHumanBandCounter++;
                // Addition of the image to the associated list
                notHumanList.add(newImage);
            }
        }
    }

    // computing final raster space for the two targets
    GridGeometry2D humanGG2D = new GridGeometry2D(PixelInCell.CELL_CORNER, new AffineTransform2D(g2WHuman),
            globalBBOXHuman, null);
    globalBBOXHuman = humanGG2D.getEnvelope2D(); // take into account integer pixel roundings

    GridGeometry2D noHumanGG2D = new GridGeometry2D(PixelInCell.CELL_CORNER, new AffineTransform2D(g2WNotHuman),
            globalBBOXNotHuman, null);
    globalBBOXNotHuman = noHumanGG2D.getEnvelope2D(); // take into account integer pixel roundings

    // BandMerge of the images
    RenderedImage[] imagesHuman = new RenderedImage[humanList.size()];
    RenderedImage[] imagesNotHuman = new RenderedImage[notHumanList.size()];
    // Setting of the final layout
    ImageLayout layoutH = new ImageLayout2();
    GridEnvelope2D gridRange2D = humanGG2D.getGridRange2D();
    layoutH.setMinX(gridRange2D.x);
    layoutH.setMinY(gridRange2D.y);
    layoutH.setWidth(gridRange2D.width);
    layoutH.setHeight(gridRange2D.height);
    // Definition of the TileCache
    RenderingHints hintsH = new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache());
    // Setting of the layout as hint
    hintsH.put(JAI.KEY_IMAGE_LAYOUT, layoutH);
    // Merging of the input human targets
    humanTargets = BandMergeDescriptor.create(null, 0, hintsH, tfHuman, humanList.toArray(imagesHuman));
    // Setting of the final layout
    ImageLayout layoutNH = new ImageLayout2();
    gridRange2D = noHumanGG2D.getGridRange2D();
    layoutNH.setMinX(gridRange2D.x);
    layoutNH.setMinY(gridRange2D.y);
    layoutNH.setWidth(gridRange2D.width);
    layoutNH.setHeight(gridRange2D.height);
    // Definition of the TileCache
    RenderingHints hintsNH = new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache());
    hintsNH.put(JAI.KEY_IMAGE_LAYOUT, layoutNH);
    // Merging of the input not human targets
    notHumanTargets = BandMergeDescriptor.create(null, 0, hintsNH, tfNotHuman,
            notHumanList.toArray(imagesNotHuman));

    // cache the final images
    humanTargets = NullDescriptor.create(humanTargets,
            new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache()));

    notHumanTargets = NullDescriptor.create(notHumanTargets,
            new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache()));

    // Clearing of the initial lists
    notHumanList.clear();
    humanList.clear();
    // create a new array of the new images
    return new RenderedImage[] { humanTargets, notHumanTargets };
}

From source file:org.pmedv.blackboard.components.BoardEditor.java

@Override
protected void paintComponent(Graphics g) {
    Boolean useLayerColor = (Boolean) Preferences.values
            .get("org.pmedv.blackboard.BoardDesignerPerspective.useLayerColor");

    // clear all      
    // g.clearRect(0, 0, getWidth(), getHeight());
    g.setColor(BLANK);/*  w w  w. j  a va 2s  .com*/
    g.fillRect(0, 0, getWidth(), getHeight());
    // some nice anti aliasing...
    Graphics2D g2 = (Graphics2D) g;
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2.setRenderingHints(rh);

    // TODO : Should this be done here?
    // Sort layers by z-index

    g2.setColor(Color.LIGHT_GRAY);
    g2.setStroke(BoardUtil.stroke_1_0f);

    Collections.sort(model.getLayers());
    for (int i = model.getLayers().size() - 1; i >= 0; i--) {
        // Sort items by z-index
        Collections.sort(model.getLayers().get(i).getItems());
        drawLayer(model.getLayers().get(i), g2);
    }

    // draw selection border
    if (state.equals(SelectionState.DRAGGING_NEW_SELECTION) && button1Pressed) {
        g2.setColor(Color.GREEN);
        g2.setStroke(BoardUtil.stroke_1_0f);
        if (dragStopX < dragStartX && dragStopY > dragStartY) {
            selectionBorder.setSize(dragStartX - dragStopX, dragStopY - dragStartY);
            selectionBorder.setLocation(dragStopX, dragStartY);
        } else if (dragStopY < dragStartY && dragStopX > dragStartX) {
            selectionBorder.setSize(dragStopX - dragStartX, dragStartY - dragStopY);
            selectionBorder.setLocation(dragStartX, dragStopY);
        } else if (dragStopX < dragStartX && dragStopY < dragStartY) {
            selectionBorder.setSize(dragStartX - dragStopX, dragStartY - dragStopY);
            selectionBorder.setLocation(dragStopX, dragStopY);
        } else {
            selectionBorder.setSize(dragStopX - dragStartX, dragStopY - dragStartY);
            selectionBorder.setLocation(dragStartX, dragStartY);
        }
        g2.draw(selectionBorder);
    }
    // display shape currently being drawed
    if (lineStartX > 0 && lineStartY > 0 && lineStopX > 0 && lineStopY > 0) {

        if (useLayerColor)
            g2.setColor(model.getCurrentLayer().getColor());
        else
            g2.setColor(palette.getCurrentColor());

        g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
        // draw new line
        if (editorMode.equals(EditorMode.DRAW_LINE)) {

            if (useLayerColor)
                currentDrawingLine.setColor(model.getCurrentLayer().getColor());
            else
                currentDrawingLine.setColor(palette.getCurrentColor());

            currentDrawingLine.setStartType((LineEdgeType) shapesPanel.getStartLineCombo().getSelectedItem());
            currentDrawingLine.setEndType((LineEdgeType) shapesPanel.getEndLineCombo().getSelectedItem());
            currentDrawingLine.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
            currentDrawingLine.getStart().setLocation(lineStartX, lineStartY);
            currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY);
            currentDrawingLine.draw(g2);
        } else if (editorMode.equals(EditorMode.DRAW_MEASURE)) {
            currentDrawingLine.setStroke(Measure.DEFAULT_STROKE);
            currentDrawingLine.getStart().setLocation(lineStartX, lineStartY);
            currentDrawingLine.getEnd().setLocation(lineStopX, lineStopY);
            currentDrawingLine.draw(g2);
        }
        // draw new box or ellipse
        else if (editorMode.equals(EditorMode.DRAW_RECTANGLE) || editorMode.equals(EditorMode.DRAW_ELLIPSE)) {
            int xLoc = lineStartX;
            int yLoc = lineStartY;
            int width = lineStopX - lineStartX;
            int height = lineStopY - lineStartY;
            ShapeStyle style = (ShapeStyle) shapesPanel.getStyleCombo().getSelectedItem();
            if (style == null || style.equals(ShapeStyle.FILLED)) {
                if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) {
                    g2.fillRect(xLoc, yLoc, width, height);
                } else {
                    g2.fillOval(xLoc, yLoc, width, height);
                }
            } else if (style.equals(ShapeStyle.OUTLINED)) {
                g2.setStroke((BasicStroke) shapesPanel.getThicknessCombo().getSelectedItem());
                if (editorMode.equals(EditorMode.DRAW_RECTANGLE)) {
                    g2.drawRect(xLoc, yLoc, width, height);
                } else {
                    g2.drawOval(xLoc, yLoc, width, height);
                }
            }
        }
    }
    // draw selection handles
    if (selectedItem != null) {
        g2.setStroke(BoardUtil.stroke_1_0f);
        g2.setColor(Color.GREEN);
        selectedItem.drawHandles(g2, 8);
    }

    // draw border

    if (zoomLayer != null) {
        TransformUI ui = (TransformUI) (Object) zoomLayer.getUI();
        DefaultTransformModel xmodel = (DefaultTransformModel) ui.getModel();

        if (xmodel.isMirror()) {
            g2.setColor(Color.RED);
        } else {
            g2.setColor(Color.GREEN);
        }
    } else {
        g2.setColor(Color.GREEN);
    }

    g2.setStroke(DEFAULT_STROKE);

    Rectangle border = new Rectangle(0, 0, model.getWidth() - 1, model.getHeight() - 1);
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
    g2.draw(border);

    if (model.getType().equals(BoardType.STRIPES) || model.getType().equals(BoardType.HOLES)) {

        g2.setColor(Color.BLACK);
        g2.setFont(miniFont);

        int index = 1;

        for (int x = 12; x < model.getWidth() - 16; x += 16) {
            g2.drawString(String.valueOf(index++), x, 8);
        }

        index = 1;

        for (int y = 18; y < model.getHeight(); y += 16) {
            g2.drawString(String.valueOf(index++), 3, y);
        }

    }

    if (editorMode.equals(EditorMode.CHECK_CONNECTIONS)) {
        if (connectedLines != null) {
            for (Line line : connectedLines) {
                line.drawFat(g2);
            }
        }
    }

    if (drawing) {

        g2.setColor(Color.BLUE);
        g2.setStroke(DEFAULT_STROKE);

        if (selectedPin != null) {
            g2.drawRect(lineStopX - 8, lineStopY - 8, 16, 16);
        }

    }

    super.paintComponents(g2);
}

From source file:edmondskarp.Gui.EdmondsKarpGui.java

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    ((Graphics2D) g).setRenderingHints(rh);
    gui.update(g);/*w  w  w . j  a  v  a 2  s.co  m*/
}