List of usage examples for java.awt Rectangle setRect
public void setRect(Rectangle2D r)
From source file:SwingUtil.java
/** * Verifies if the given point is visible on the screen. * //from www .ja va 2 s.c o m * @param location The given location on the screen. * @return True if the location is on the screen, false otherwise. */ public static boolean isLocationInScreenBounds(Point location) { // Check if the location is in the bounds of one of the graphics devices. GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] graphicsDevices = graphicsEnvironment.getScreenDevices(); Rectangle graphicsConfigurationBounds = new Rectangle(); // Iterate over the graphics devices. for (int j = 0; j < graphicsDevices.length; j++) { // Get the bounds of the device. GraphicsDevice graphicsDevice = graphicsDevices[j]; graphicsConfigurationBounds.setRect(graphicsDevice.getDefaultConfiguration().getBounds()); // Is the location in this bounds? graphicsConfigurationBounds.setRect(graphicsConfigurationBounds.x, graphicsConfigurationBounds.y, graphicsConfigurationBounds.width, graphicsConfigurationBounds.height); if (graphicsConfigurationBounds.contains(location.x, location.y)) { // The location is in this screengraphics. return true; } } // We could not find a device that contains the given point. return false; }
From source file:org.geotools.coverage.io.util.Utilities.java
/** * Returns the intersection between the base envelope and the requested envelope. * /*from w w w . ja va 2 s. co m*/ * @param baseEnvelope2D the base envelope. * * @param requestedEnvelope2D the requested 2D envelope to be intersected with the base envelope. * @param requestedDim is the requested region where to load data of the specified envelope. * @param readGridToWorld the Grid to world transformation to be used in read * @param wgs84BaseEnvelope2D a WGS84 version of the baseEnvelope to be used to try finding an intersection in wgs84 in case it is impossible to * compute an intersection of the base envelope with the specified requested envelope. * @return the resulting intersection of envelopes. In case of empty intersection, this method is allowed to return {@code null} * @throws TransformException * @throws FactoryException * @todo TODO XXX refactor this method leveraging on the coverageSourceCapabilities of reprojection. Moreover add a boolean parameter saying if * trying to reproject to WGS84 always need to be done */ public static GeneralEnvelope getIntersection(final Envelope2D baseEnvelope2D, final CoordinateReferenceSystem spatialReferenceSystem2D, GeneralEnvelope requestedEnvelope2D, Rectangle requestedDim, MathTransform2D readGridToWorld, final Envelope2D wgs84BaseEnvelope2D) throws TransformException, FactoryException { if (baseEnvelope2D == null || spatialReferenceSystem2D == null || requestedEnvelope2D == null || requestedDim == null || readGridToWorld == null) { StringBuilder sb = new StringBuilder("Some of the specified parameters are null:") .append(baseEnvelope2D == null ? "base envelope \n" : "") .append(spatialReferenceSystem2D == null ? "native spatial reference system\n" : "") .append(requestedEnvelope2D == null ? "requested envelope \n" : "") .append(requestedDim == null ? "requested dim\n" : "") .append(readGridToWorld == null ? "requested grid to world transformation \n" : ""); throw new IllegalArgumentException(sb.toString()); } GeneralEnvelope adjustedRequestedEnvelope = new GeneralEnvelope(2); final CoordinateReferenceSystem requestedEnvelopeCRS2D = requestedEnvelope2D.getCoordinateReferenceSystem(); boolean tryWithWGS84 = false; try { // convert the requested envelope 2D to this coverage native crs. MathTransform transform = null; if (!CRS.equalsIgnoreMetadata(requestedEnvelopeCRS2D, spatialReferenceSystem2D)) transform = CRS.findMathTransform(requestedEnvelopeCRS2D, spatialReferenceSystem2D, true); // now transform the requested envelope to source crs if (transform != null && !transform.isIdentity()) adjustedRequestedEnvelope = CRS.transform(transform, requestedEnvelope2D); else adjustedRequestedEnvelope.setEnvelope(requestedEnvelope2D); // intersect the requested area with the bounds of this // layer in native crs if (!adjustedRequestedEnvelope.intersects(baseEnvelope2D, true)) return null; adjustedRequestedEnvelope.intersect(baseEnvelope2D); adjustedRequestedEnvelope.setCoordinateReferenceSystem(spatialReferenceSystem2D); // // // // transform the intersection envelope from the destination world // space to the requested raster space // // // final Envelope requestedEnvelopeCropped = (transform != null && !transform.isIdentity()) ? CRS.transform(transform.inverse(), adjustedRequestedEnvelope) : adjustedRequestedEnvelope; final Rectangle2D ordinates = CRS.transform(readGridToWorld.inverse(), requestedEnvelopeCropped) .toRectangle2D(); final GeneralGridEnvelope finalRange = new GeneralGridEnvelope(ordinates.getBounds()); final Rectangle tempRect = finalRange.toRectangle(); // check that we stay inside the source rectangle XRectangle2D.intersect(tempRect, requestedDim, tempRect); requestedDim.setRect(tempRect); } catch (TransformException te) { // something bad happened while trying to transform this // envelope. let's try with wgs84 tryWithWGS84 = true; } catch (FactoryException fe) { // something bad happened while trying to transform this // envelope. let's try with wgs84 tryWithWGS84 = true; } // // // // If this does not work, we go back to reproject in the wgs84 // requested envelope // // // if (tryWithWGS84) { final GeneralEnvelope requestedEnvelopeWGS84 = (GeneralEnvelope) getEnvelopeAsWGS84(requestedEnvelope2D, false); // checking the intersection in wgs84 if (!requestedEnvelopeWGS84.intersects(wgs84BaseEnvelope2D, true)) return null; // intersect adjustedRequestedEnvelope = new GeneralEnvelope(requestedEnvelopeWGS84); adjustedRequestedEnvelope.intersect(wgs84BaseEnvelope2D); adjustedRequestedEnvelope = CRS .transform(CRS.findMathTransform(requestedEnvelopeWGS84.getCoordinateReferenceSystem(), spatialReferenceSystem2D, true), adjustedRequestedEnvelope); adjustedRequestedEnvelope.setCoordinateReferenceSystem(spatialReferenceSystem2D); } return adjustedRequestedEnvelope; }
From source file:org.geotools.coverage.io.util.Utilities.java
/** * Evaluates the requested envelope and builds a new adjusted version of it fitting this coverage envelope. * // w ww . j a v a 2 s . co m * <p> * While adjusting the requested envelope this methods also compute the source region as a rectangle which is suitable for a successive read * operation with {@link ImageIO} to do crop-on-read. * * @param originalGridToWorld * * @param coordinateReferenceSystem * * * @param requestedEnvelope is the envelope we are requested to load. * @param sourceRegion represents the area to load in raster space. This parameter cannot be null since it gets filled with whatever the crop * region is depending on the <code>requestedEnvelope</code>. * @param requestedDim is the requested region where to load data of the specified envelope. * @param readGridToWorld the Grid to world transformation to be used * @param wgs84BaseEnvelope2D * @return the adjusted requested envelope, empty if no requestedEnvelope has been specified, {@code null} in case the requested envelope does not * intersect the coverage envelope or in case the adjusted requested envelope is covered by a too small raster region (an empty region). * * @throws DataSourceException in case something bad occurs */ public static GeneralEnvelope evaluateRequestedParams(GridEnvelope originalGridRange, Envelope2D baseEnvelope2D, CoordinateReferenceSystem spatialReferenceSystem2D, MathTransform originalGridToWorld, GeneralEnvelope requestedEnvelope, Rectangle sourceRegion, Rectangle requestedDim, MathTransform2D readGridToWorld, Envelope2D wgs84BaseEnvelope2D) throws DataSourceException { GeneralEnvelope adjustedRequestedEnvelope = new GeneralEnvelope(2); GeneralGridEnvelope baseGridRange = (GeneralGridEnvelope) originalGridRange; try { // //////////////////////////////////////////////////////////////// // // Check if we have something to load by intersecting the // requested envelope with the bounds of this data set. // // //////////////////////////////////////////////////////////////// if (requestedEnvelope != null) { final GeneralEnvelope requestedEnvelope2D = Utilities.getRequestedEnvelope2D(requestedEnvelope); // //////////////////////////////////////////////////////////// // // INTERSECT ENVELOPES AND CROP Destination REGION // // //////////////////////////////////////////////////////////// adjustedRequestedEnvelope = Utilities.getIntersection(baseEnvelope2D, spatialReferenceSystem2D, requestedEnvelope2D, requestedDim, readGridToWorld, wgs84BaseEnvelope2D); if (adjustedRequestedEnvelope == null) return null; // ///////////////////////////////////////////////////////////////////// // // CROP SOURCE REGION // // ///////////////////////////////////////////////////////////////////// sourceRegion.setRect(Utilities.getCropRegion(adjustedRequestedEnvelope, Utilities.getOriginalGridToWorld(originalGridToWorld, PixelInCell.CELL_CORNER))); if (sourceRegion.isEmpty()) { if (LOGGER.isLoggable(Level.INFO)) { LOGGER.log(Level.INFO, "Too small envelope resulting in empty cropped raster region"); } return null; // TODO: Future versions may define a 1x1 rectangle starting // from the lower coordinate } if (!sourceRegion.intersects(baseGridRange.toRectangle()) || sourceRegion.isEmpty()) throw new DataSourceException("The crop region is invalid."); sourceRegion.setRect(sourceRegion.intersection(baseGridRange.toRectangle())); if (LOGGER.isLoggable(Level.FINE)) { StringBuilder sb = new StringBuilder("Adjusted Requested Envelope = ") .append(adjustedRequestedEnvelope.toString()).append("\n") .append("Requested raster dimension = ").append(requestedDim.toString()).append("\n") .append("Corresponding raster source region = ").append(sourceRegion.toString()); LOGGER.log(Level.FINE, sb.toString()); } } else { // don't use the source region. Set an empty one sourceRegion.setBounds(new Rectangle(0, 0, Integer.MIN_VALUE, Integer.MIN_VALUE)); } } catch (TransformException e) { throw new DataSourceException("Unable to create a coverage for this source", e); } catch (FactoryException e) { throw new DataSourceException("Unable to create a coverage for this source", e); } return adjustedRequestedEnvelope; }
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 .jav a 2 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(); } } } }