Java Code Examples for java.awt.image.RenderedImage#getWidth()

The following examples show how to use java.awt.image.RenderedImage#getWidth() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PrintUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Print data from a {@link RenderedImage}.
 * 
 * @param renderedImage
 *            the image.
 */
public static void printRenderedImageData( RenderedImage renderedImage ) {
    RandomIter iter = RandomIterFactory.create(renderedImage, null);
    int cols = renderedImage.getWidth();
    int rows = renderedImage.getHeight();
    int numBands = renderedImage.getSampleModel().getNumBands();
    for( int r = 0; r < rows; r++ ) {
        for( int c = 0; c < cols; c++ ) {
            for( int b = 0; b < numBands; b++ ) {
                if (b > 0) {
                    printer.print("/");
                }
                printer.print(iter.getSampleDouble(c, r, b));
            }
            printer.print(separator);
        }
        printer.println();
    }
    iter.done();
}
 
Example 2
Source File: GraphicsUtils.java    From jfreesvg with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Converts a rendered image to a {@code BufferedImage}.  This utility
 * method has come from a forum post by Jim Moore at:
 * <p>
 * <a href="http://www.jguru.com/faq/view.jsp?EID=114602">
 * http://www.jguru.com/faq/view.jsp?EID=114602</a>
 * 
 * @param img  the rendered image ({@code null} not permitted).
 * 
 * @return A buffered image. 
 */
public static BufferedImage convertRenderedImage(RenderedImage img) {
    Args.nullNotPermitted(img, "img");
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;	
    }
    ColorModel cm = img.getColorModel();
    int width = img.getWidth();
    int height = img.getHeight();
    WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    Hashtable properties = new Hashtable();
    String[] keys = img.getPropertyNames();
    if (keys != null) {
        for (int i = 0; i < keys.length; i++) {
            properties.put(keys[i], img.getProperty(keys[i]));
        }
    }
    BufferedImage result = new BufferedImage(cm, raster, 
            isAlphaPremultiplied, properties);
    img.copyData(raster);
    return result;
}
 
Example 3
Source File: JaiLoader.java    From libreveris with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Try to load an image, using JAI.
 * This seems limited to a single image, thus no id parameter is to be
 * provided.
 *
 * @param imgFile the input file
 * @return a map of one image, or null if failed to load
 */
public static SortedMap<Integer, RenderedImage> loadJAI (File imgFile)
{
    RenderedImage image = JAI.create("fileload", imgFile.getPath());

    try {
        if ((image.getWidth() > 0) && (image.getHeight() > 0)) {
            SortedMap<Integer, RenderedImage> images = new TreeMap<>();
            images.put(1, image);

            return images;
        }
    } catch (Exception ex) {
        logger.debug(ex.getMessage());
    }

    return null;
}
 
Example 4
Source File: FXGraphics2D.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Converts a rendered image to a {@code BufferedImage}.  This utility
 * method has come from a forum post by Jim Moore at:
 * <p>
 * <a href="http://www.jguru.com/faq/view.jsp?EID=114602">
 * http://www.jguru.com/faq/view.jsp?EID=114602</a>
 * 
 * @param img  the rendered image.
 * 
 * @return A buffered image. 
 */
private static BufferedImage convertRenderedImage(RenderedImage img) {
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }
    ColorModel cm = img.getColorModel();
    int width = img.getWidth();
    int height = img.getHeight();
    WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    Hashtable properties = new Hashtable();
    String[] keys = img.getPropertyNames();
    if (keys != null) {
        for (int i = 0; i < keys.length; i++) {
            properties.put(keys[i], img.getProperty(keys[i]));
        }
    }
    BufferedImage result = new BufferedImage(cm, raster, 
            isAlphaPremultiplied, properties);
    img.copyData(raster);
    return result;
}
 
Example 5
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public static WritableRaster renderedImage2ShortWritableRaster( RenderedImage renderedImage, boolean nullBorders ) {
    int width = renderedImage.getWidth();
    int height = renderedImage.getHeight();

    Raster data = renderedImage.getData();
    WritableRaster writableRaster = createWritableRaster(width, height, Short.class, null, null);
    writableRaster.setRect(data);
    if (nullBorders) {
        for( int c = 0; c < width; c++ ) {
            writableRaster.setSample(c, 0, 0, shortNovalue);
            writableRaster.setSample(c, height - 1, 0, shortNovalue);
        }
        for( int r = 0; r < height; r++ ) {
            writableRaster.setSample(0, r, 0, shortNovalue);
            writableRaster.setSample(width - 1, r, 0, shortNovalue);
        }
    }
    return writableRaster;
}
 
Example 6
Source File: FXGraphics2D.java    From ECG-Viewer with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Converts a rendered image to a {@code BufferedImage}.  This utility
 * method has come from a forum post by Jim Moore at:
 * <p>
 * <a href="http://www.jguru.com/faq/view.jsp?EID=114602">
 * http://www.jguru.com/faq/view.jsp?EID=114602</a>
 * 
 * @param img  the rendered image.
 * 
 * @return A buffered image. 
 */
private static BufferedImage convertRenderedImage(RenderedImage img) {
    if (img instanceof BufferedImage) {
        return (BufferedImage) img;
    }
    ColorModel cm = img.getColorModel();
    int width = img.getWidth();
    int height = img.getHeight();
    WritableRaster raster = cm.createCompatibleWritableRaster(width, height);
    boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
    Hashtable properties = new Hashtable();
    String[] keys = img.getPropertyNames();
    if (keys != null) {
        for (int i = 0; i < keys.length; i++) {
            properties.put(keys[i], img.getProperty(keys[i]));
        }
    }
    BufferedImage result = new BufferedImage(cm, raster, 
            isAlphaPremultiplied, properties);
    img.copyData(raster);
    return result;
}
 
Example 7
Source File: WritablePixelIterator.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an iterator for the given region in the given image.
 *
 * @param  input    the image which contains the sample values to read.
 * @param  output   the image where to write the sample values, or {@code null} for read-only iterator.
 * @param  subArea  the image region where to perform the iteration, or {@code null}
 *                  for iterating over all the image domain.
 * @param  window   size of the window to use in {@link #createWindow(TransferType)} method, or {@code null} if none.
 */
WritablePixelIterator(final RenderedImage input, final WritableRenderedImage output,
                      final Rectangle subArea, final Dimension window)
{
    super(input, subArea, window);
    destRaster  = null;
    destination = output;
    if (output != null) {
        if (!input.getSampleModel().equals(output.getSampleModel())) {
            throw new IllegalArgumentException(Resources.format(Resources.Keys.MismatchedSampleModel));
        } else if (input.getMinX()   != output.getMinX()  ||
                   input.getMinY()   != output.getMinY()  ||
                   input.getWidth()  != output.getWidth() ||
                   input.getHeight() != output.getHeight())
        {
            throw new IllegalArgumentException(Resources.format(Resources.Keys.MismatchedImageLocation));
        } else if (input.getMinTileX()   != output.getMinTileX()  ||
                   input.getMinTileY()   != output.getMinTileY()  ||
                   input.getTileWidth()  != output.getTileWidth() ||
                   input.getTileHeight() != output.getTileHeight())
        {
            throw new IllegalArgumentException(Resources.format(Resources.Keys.MismatchedTileGrid));
        }
    }
}
 
Example 8
Source File: BinarizeDescriptor.java    From pdfxtk with Apache License 2.0 6 votes vote down vote up
/** Creates an BinarizeOpImage with a given ParameterBlock */

  public RenderedImage create(ParameterBlock paramBlock, 
			      RenderingHints renderingHints)
  {
    RenderedImage img = paramBlock.getRenderedSource(0);

    ImageLayout il = new ImageLayout(img);
    ColorModel cm = new IndexColorModel(1, 2, bwColors, bwColors, bwColors);
    SampleModel sm = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
						     img.getWidth(),
						     img.getHeight(),
						     1);

    il.setColorModel(cm);
    il.setSampleModel(sm);

    return new BinarizeOpImage(paramBlock.getRenderedSource(0),
			       renderingHints,
			       il,
			       (Integer)paramBlock.getObjectParameter(0));
  }
 
Example 9
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public static WritableRaster renderedImage2DoubleWritableRaster( RenderedImage renderedImage, boolean nullBorders ) {
    int width = renderedImage.getWidth();
    int height = renderedImage.getHeight();

    Raster data = renderedImage.getData();
    WritableRaster writableRaster = createWritableRaster(width, height, Double.class, null, null);
    writableRaster.setRect(data);
    if (nullBorders) {
        for( int c = 0; c < width; c++ ) {
            writableRaster.setSample(c, 0, 0, doubleNovalue);
            writableRaster.setSample(c, height - 1, 0, doubleNovalue);
        }
        for( int r = 0; r < height; r++ ) {
            writableRaster.setSample(0, r, 0, doubleNovalue);
            writableRaster.setSample(width - 1, r, 0, doubleNovalue);
        }
    }
    return writableRaster;
}
 
Example 10
Source File: OmsLabeler.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Execute
public void process() throws Exception {
    if (!concatOr(outMap == null, doReset)) {
        return;
    }

    final RenderedImage renderedImage = inMap.getRenderedImage();
    int width = renderedImage.getWidth();
    int height = renderedImage.getHeight();
    int[] data = new int[width * height];
    RandomIter iter = RandomIterFactory.create(renderedImage, null);
    int index = 0;
    for( int r = 0; r < height; r++ ) {
        for( int c = 0; c < width; c++ ) {
            double value = iter.getSampleDouble(c, r, 0);
            if (isNovalue(value)) {
                data[index] = BinaryFast.BACKGROUND;
            } else {
                data[index] = BinaryFast.FOREGROUND;
            }
            index++;
        }
    }

    int[] labelsArray = doLabel(data, width, height);

    WritableRaster dataWR = CoverageUtilities.createWritableRasterFromArray(width, height, labelsArray);
    HashMap<String, Double> regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inMap);
    outMap = CoverageUtilities.buildCoverage("labeled", dataWR, regionMap, inMap.getCoordinateReferenceSystem()); //$NON-NLS-1$
}
 
Example 11
Source File: OmsHillshade.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Execute
public void process() throws Exception {
    // Check on the input parameters
    checkNull(inElev);
    if (pAzimuth < 0.0 || pAzimuth > 360.0) {
        System.err.println(msg.message("hillshade.errAzimuth"));
    }
    if (pElev < 0.0 || pElev > 90.0) {
        System.err.println(msg.message("hillshade.errElevation"));
    }
    RenderedImage pitRI = inElev.getRenderedImage();
    WritableRaster pitWR = CoverageUtilities.replaceNovalue(pitRI, -9999.0);
    // extract some attributes of the dem
    HashMap<String, Double> attribute = CoverageUtilities.getRegionParamsFromGridCoverage(inElev);
    double dx = attribute.get(CoverageUtilities.XRES);
    int width = pitRI.getWidth();
    int height = pitRI.getHeight();
    pitRI = null;

    WritableRaster hillshadeWR = CoverageUtilities.createWritableRaster(width, height, null, pitWR.getSampleModel(),
            0.0);
    WritableRaster gradientWR = normalVector(pitWR, dx);

    calchillshade(pitWR, hillshadeWR, gradientWR, dx);

    // re-set the value to NaN
    setNoValueBorder(pitWR, width, height, hillshadeWR);

    outHill = CoverageUtilities.buildCoverage("insolation", hillshadeWR, attribute, inElev.getCoordinateReferenceSystem());
}
 
Example 12
Source File: CCOpImage.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
/** Constructs a CCOpImage object */

  public CCOpImage(RenderedImage source, Rectangle sample) {
    super(source, new ROIShape(new Rectangle(source.getMinX(), source.getMinY(), 
					     source.getWidth(), source.getHeight())),
	  source.getMinX(), source.getMinY(),
	  1, 1);

    sampleRectangle = sample;
    image = source;
  }
 
Example 13
Source File: SunGraphics2D.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a rectangle in image coordinates that may be required
 * in order to draw the given image into the given clipping region
 * through a pair of AffineTransforms.  In addition, horizontal and
 * vertical padding factors for antialising and interpolation may
 * be used.
 */
private static Rectangle getImageRegion(RenderedImage img,
                                        Region compClip,
                                        AffineTransform transform,
                                        AffineTransform xform,
                                        int padX, int padY) {
    Rectangle imageRect =
        new Rectangle(img.getMinX(), img.getMinY(),
                      img.getWidth(), img.getHeight());

    Rectangle result = null;
    try {
        double p[] = new double[8];
        p[0] = p[2] = compClip.getLoX();
        p[4] = p[6] = compClip.getHiX();
        p[1] = p[5] = compClip.getLoY();
        p[3] = p[7] = compClip.getHiY();

        // Inverse transform the output bounding rect
        transform.inverseTransform(p, 0, p, 0, 4);
        xform.inverseTransform(p, 0, p, 0, 4);

        // Determine a bounding box for the inverse transformed region
        double x0,x1,y0,y1;
        x0 = x1 = p[0];
        y0 = y1 = p[1];

        for (int i = 2; i < 8; ) {
            double pt = p[i++];
            if (pt < x0)  {
                x0 = pt;
            } else if (pt > x1) {
                x1 = pt;
            }
            pt = p[i++];
            if (pt < y0)  {
                y0 = pt;
            } else if (pt > y1) {
                y1 = pt;
            }
        }

        // This is padding for anti-aliasing and such.  It may
        // be more than is needed.
        int x = (int)x0 - padX;
        int w = (int)(x1 - x0 + 2*padX);
        int y = (int)y0 - padY;
        int h = (int)(y1 - y0 + 2*padY);

        Rectangle clipRect = new Rectangle(x,y,w,h);
        result = clipRect.intersection(imageRect);
    } catch (NoninvertibleTransformException nte) {
        // Worst case bounds are the bounds of the image.
        result = imageRect;
    }

    return result;
}
 
Example 14
Source File: PixelInfoViewModelUpdater.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
private boolean coordinatesAreInRasterBounds(RasterDataNode raster, int x, int y, int level) {
    final RenderedImage levelImage = raster.getSourceImage().getImage(level);
    return x >= 0 && y >= 0 && x < levelImage.getWidth() && y < levelImage.getHeight();
}
 
Example 15
Source File: SunGraphics2D.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a rectangle in image coordinates that may be required
 * in order to draw the given image into the given clipping region
 * through a pair of AffineTransforms.  In addition, horizontal and
 * vertical padding factors for antialising and interpolation may
 * be used.
 */
private static Rectangle getImageRegion(RenderedImage img,
                                        Region compClip,
                                        AffineTransform transform,
                                        AffineTransform xform,
                                        int padX, int padY) {
    Rectangle imageRect =
        new Rectangle(img.getMinX(), img.getMinY(),
                      img.getWidth(), img.getHeight());

    Rectangle result = null;
    try {
        double p[] = new double[8];
        p[0] = p[2] = compClip.getLoX();
        p[4] = p[6] = compClip.getHiX();
        p[1] = p[5] = compClip.getLoY();
        p[3] = p[7] = compClip.getHiY();

        // Inverse transform the output bounding rect
        transform.inverseTransform(p, 0, p, 0, 4);
        xform.inverseTransform(p, 0, p, 0, 4);

        // Determine a bounding box for the inverse transformed region
        double x0,x1,y0,y1;
        x0 = x1 = p[0];
        y0 = y1 = p[1];

        for (int i = 2; i < 8; ) {
            double pt = p[i++];
            if (pt < x0)  {
                x0 = pt;
            } else if (pt > x1) {
                x1 = pt;
            }
            pt = p[i++];
            if (pt < y0)  {
                y0 = pt;
            } else if (pt > y1) {
                y1 = pt;
            }
        }

        // This is padding for anti-aliasing and such.  It may
        // be more than is needed.
        int x = (int)x0 - padX;
        int w = (int)(x1 - x0 + 2*padX);
        int y = (int)y0 - padY;
        int h = (int)(y1 - y0 + 2*padY);

        Rectangle clipRect = new Rectangle(x,y,w,h);
        result = clipRect.intersection(imageRect);
    } catch (NoninvertibleTransformException nte) {
        // Worst case bounds are the bounds of the image.
        result = imageRect;
    }

    return result;
}
 
Example 16
Source File: OmsRasterSummary.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    if (!concatOr(outMin == null, doReset)) {
        return;
    }
    
    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inRaster);
    pm.message("Bounds and resolution");
    pm.message("---------------------");
    pm.message(regionMap.toStringJGT());
    pm.message("");
    pm.message("Coordinate Reference System");
    pm.message("---------------------------");
    pm.message(inRaster.getCoordinateReferenceSystem().toWKT());
    pm.message("");
    

    // TODO use the geotools bridge instead of jaitools:
    // http://svn.osgeo.org/geotools/trunk/modules/library/coverage/src/test/java/org/geotools/coverage/processing/operation/ZonalStasTest.java

    RenderedImage inRI = inRaster.getRenderedImage();
    Polygon regionPolygon = CoverageUtilities.getRegionPolygon(inRaster);
    SimpleFeatureCollection regionFC = FeatureUtilities.featureCollectionFromGeometry(inRaster.getCoordinateReferenceSystem(),
            regionPolygon);

    OmsZonalStats zs = new OmsZonalStats();
    zs.pm = new DummyProgressMonitor();
    zs.inRaster = inRaster;
    zs.inVector = regionFC;
    zs.pPercentageThres = 0;
    zs.process();
    SimpleFeatureCollection outVector = zs.outVector;
    List<SimpleFeature> testList = FeatureUtilities.featureCollectionToList(outVector);
    SimpleFeature feature = testList.get(0);

    if (stats == null) {
        stats = new String[]{Variables.MIN, Variables.MAX, Variables.AVG, Variables.SDEV, Variables.VAR, Variables.SUM};
    }

    for( String statName : stats ) {
        Object attribute = feature.getAttribute(statName);
        if (attribute != null) {
            switch( statName ) {
            case Variables.MIN:
                outMin = (Double) attribute;
                break;
            case Variables.MAX:
                outMax = (Double) attribute;
                break;
            case Variables.AVG:
                outMean = (Double) attribute;
                break;
            case Variables.SDEV:
                outSdev = (Double) attribute;
                break;
            case Variables.SUM:
                outSum = (Double) attribute;
                break;

            default:
                break;
            }
        }
    }

    if (outMin != null && outMax != null) {
        outRange = outMax - outMin;
    }
    if (!doHistogram)
        return;

    double[][] cb = new CoupledFieldsMoments().process(inRI, null, pBins, 1, 2, pm, 1);

    int width = inRI.getWidth();
    int height = inRI.getHeight();
    int pixelsNum = width * height;
    outCb = new double[cb.length + 1][3];

    double sum = 0;
    for( int i = 0; i < outCb.length; i++ ) {
        if (i < outCb.length - 1) {
            outCb[i][0] = cb[i][0];
            outCb[i][1] = cb[i][1];
            sum = sum + cb[i][1];
            outCb[i][2] = cb[i][1] * 100.0 / pixelsNum;
        } else {
            outCb[i][0] = HMConstants.doubleNovalue;
            double nans = pixelsNum - sum;
            outCb[i][1] = nans;
            outCb[i][2] = nans * 100.0 / pixelsNum;
        }

    }

}
 
Example 17
Source File: ImageCompareUtil.java    From qaf with MIT License 4 votes vote down vote up
public boolean contains(String reference, String template, Point start) throws Exception {
	RenderedImage ref = (ImageIO.read(new File(reference)));

	// Calculate the signature vector for the reference.
	// Now we need a component to store X images in a stack, where X is the
	// number of images in the same directory as the original one.
	// For each image, calculate its signature and its distance from the
	// reference signature.
	RenderedImage other = ImageIO.read(new File(template));

	int x, y, h, w, th, tw;
	double distance = Double.MAX_VALUE;
	h = ref.getHeight();
	w = ref.getWidth();
	System.out.println("px width: " + ref.getData().getWidth() + "px height: " + ref.getData().getHeight());
	System.out.println("width: " + ref.getWidth() + "height: " + ref.getHeight());
	System.out.println("min x: " + ref.getData().getMinX() + " y: " + ref.getData().getMinY());

	th = other.getHeight();
	tw = other.getWidth();

	for (int r = 0; r <= (h - th); r += 5) {
		for (int c = 0; c <= (w - tw); c += 5) {
			ParameterBlock pb = new ParameterBlock();
			pb.addSource(ref);
			pb.add((float) c);
			pb.add((float) r);
			pb.add((float) tw);
			pb.add((float) th);
			pb.add(new InterpolationNearest());
			// Creates a new, scaled image and uses it on the DisplayJAI
			// component

			try {
				double tdistance = calcDistance(rescale(JAI.create("crop", pb)), rescale(other));
				if ((tdistance < distance)) {
					distance = tdistance;
				}

				if (distance == 0) {
					break;
				}
				System.out.println("distance" + distance + " x: " + r + " y: " + c);
			} catch (Exception e) {
				System.out.print("Error: " + e.toString());
				e.printStackTrace();
			}
		}

		if (distance == 0) {
			break;
		}
	}
	return distance < maxDiff;
}
 
Example 18
Source File: SunGraphics2D.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a rectangle in image coordinates that may be required
 * in order to draw the given image into the given clipping region
 * through a pair of AffineTransforms.  In addition, horizontal and
 * vertical padding factors for antialising and interpolation may
 * be used.
 */
private static Rectangle getImageRegion(RenderedImage img,
                                        Region compClip,
                                        AffineTransform transform,
                                        AffineTransform xform,
                                        int padX, int padY) {
    Rectangle imageRect =
        new Rectangle(img.getMinX(), img.getMinY(),
                      img.getWidth(), img.getHeight());

    Rectangle result = null;
    try {
        double p[] = new double[8];
        p[0] = p[2] = compClip.getLoX();
        p[4] = p[6] = compClip.getHiX();
        p[1] = p[5] = compClip.getLoY();
        p[3] = p[7] = compClip.getHiY();

        // Inverse transform the output bounding rect
        transform.inverseTransform(p, 0, p, 0, 4);
        xform.inverseTransform(p, 0, p, 0, 4);

        // Determine a bounding box for the inverse transformed region
        double x0,x1,y0,y1;
        x0 = x1 = p[0];
        y0 = y1 = p[1];

        for (int i = 2; i < 8; ) {
            double pt = p[i++];
            if (pt < x0)  {
                x0 = pt;
            } else if (pt > x1) {
                x1 = pt;
            }
            pt = p[i++];
            if (pt < y0)  {
                y0 = pt;
            } else if (pt > y1) {
                y1 = pt;
            }
        }

        // This is padding for anti-aliasing and such.  It may
        // be more than is needed.
        int x = (int)x0 - padX;
        int w = (int)(x1 - x0 + 2*padX);
        int y = (int)y0 - padY;
        int h = (int)(y1 - y0 + 2*padY);

        Rectangle clipRect = new Rectangle(x,y,w,h);
        result = clipRect.intersection(imageRect);
    } catch (NoninvertibleTransformException nte) {
        // Worst case bounds are the bounds of the image.
        result = imageRect;
    }

    return result;
}
 
Example 19
Source File: SunGraphics2D.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a rectangle in image coordinates that may be required
 * in order to draw the given image into the given clipping region
 * through a pair of AffineTransforms.  In addition, horizontal and
 * vertical padding factors for antialising and interpolation may
 * be used.
 */
private static Rectangle getImageRegion(RenderedImage img,
                                        Region compClip,
                                        AffineTransform transform,
                                        AffineTransform xform,
                                        int padX, int padY) {
    Rectangle imageRect =
        new Rectangle(img.getMinX(), img.getMinY(),
                      img.getWidth(), img.getHeight());

    Rectangle result = null;
    try {
        double p[] = new double[8];
        p[0] = p[2] = compClip.getLoX();
        p[4] = p[6] = compClip.getHiX();
        p[1] = p[5] = compClip.getLoY();
        p[3] = p[7] = compClip.getHiY();

        // Inverse transform the output bounding rect
        transform.inverseTransform(p, 0, p, 0, 4);
        xform.inverseTransform(p, 0, p, 0, 4);

        // Determine a bounding box for the inverse transformed region
        double x0,x1,y0,y1;
        x0 = x1 = p[0];
        y0 = y1 = p[1];

        for (int i = 2; i < 8; ) {
            double pt = p[i++];
            if (pt < x0)  {
                x0 = pt;
            } else if (pt > x1) {
                x1 = pt;
            }
            pt = p[i++];
            if (pt < y0)  {
                y0 = pt;
            } else if (pt > y1) {
                y1 = pt;
            }
        }

        // This is padding for anti-aliasing and such.  It may
        // be more than is needed.
        int x = (int)x0 - padX;
        int w = (int)(x1 - x0 + 2*padX);
        int y = (int)y0 - padY;
        int h = (int)(y1 - y0 + 2*padY);

        Rectangle clipRect = new Rectangle(x,y,w,h);
        result = clipRect.intersection(imageRect);
    } catch (NoninvertibleTransformException nte) {
        // Worst case bounds are the bounds of the image.
        result = imageRect;
    }

    return result;
}
 
Example 20
Source File: OmsInsolation.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception { // transform the
    checkNull(inElev, tStartDate, tEndDate);
    // extract some attributes of the map
    HashMap<String, Double> attribute = CoverageUtilities.getRegionParamsFromGridCoverage(inElev);
    double dx = attribute.get(CoverageUtilities.XRES);

    /*
     * The models use only one value of the latitude. So I have decided to
     * set it to the center of the raster. Extract the CRS of the
     * GridCoverage and transform the value of a WGS84 latitude.
     */
    CoordinateReferenceSystem sourceCRS = inElev.getCoordinateReferenceSystem2D();
    CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;

    double srcPts[] = new double[]{attribute.get(CoverageUtilities.EAST), attribute.get(CoverageUtilities.SOUTH)};

    Coordinate source = new Coordinate(srcPts[0], srcPts[1]);
    Point[] so = new Point[]{GeometryUtilities.gf().createPoint(source)};
    CrsUtilities.reproject(sourceCRS, targetCRS, so);
    // the latitude value
    lambda = Math.toRadians(so[0].getY());

    /*
     * transform the start and end date in an int value (the day in the
     * year, from 1 to 365)
     */
    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd").withZone(DateTimeZone.UTC);
    DateTime currentDatetime = formatter.parseDateTime(tStartDate);
    int startDay = currentDatetime.getDayOfYear();
    currentDatetime = formatter.parseDateTime(tEndDate);
    int endDay = currentDatetime.getDayOfYear();
    CoverageUtilities.getRegionParamsFromGridCoverage(inElev);
    RenderedImage pitTmpRI = inElev.getRenderedImage();
    int width = pitTmpRI.getWidth();
    int height = pitTmpRI.getHeight();
    WritableRaster pitWR = CoverageUtilities.replaceNovalue(pitTmpRI, -9999.0);
    pitTmpRI = null;

    WritableRaster insolationWR = CoverageUtilities.createWritableRaster(width, height, null, pitWR.getSampleModel(),
            0.0);
    WritableRandomIter insolationIterator = RandomIterFactory.createWritable(insolationWR, null);

    WritableRaster gradientWR = normalVector(pitWR, dx);

    pm.beginTask(msg.message("insolation.calculating"), endDay - startDay);

    for( int i = startDay; i <= endDay; i++ ) {
        calcInsolation(lambda, pitWR, gradientWR, insolationWR, i, dx);
        pm.worked(i - startDay);
    }
    pm.done();
    for( int y = 2; y < height - 2; y++ ) {
        for( int x = 2; x < width - 2; x++ ) {
            if (HMConstants.isNovalue(pitWR.getSampleDouble(x, y, 0))) {
                insolationIterator.setSample(x, y, 0, HMConstants.doubleNovalue);

            }
        }
    }

    outIns = CoverageUtilities.buildCoverage("insolation", insolationWR, attribute, inElev.getCoordinateReferenceSystem());
}