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

The following examples show how to use java.awt.image.RenderedImage#getHeight() . 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: 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 2
Source File: AWTImageTools.java    From scifio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Converts a java.awt.image.RenderedImage into a
 * java.awt.image.BufferedImage. This code was adapted from
 * <a href="http://www.jguru.com/faq/view.jsp?EID=114602">a jGuru post</a>.
 */
public static BufferedImage convertRenderedImage(final RenderedImage img) {
	if (img instanceof BufferedImage) return (BufferedImage) img;
	final ColorModel cm = img.getColorModel();
	final int width = img.getWidth();
	final int height = img.getHeight();
	final WritableRaster raster = cm.createCompatibleWritableRaster(width,
		height);
	final boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
	final Hashtable<String, Object> properties = new Hashtable<>();
	final String[] keys = img.getPropertyNames();
	if (keys != null) {
		for (int i = 0; i < keys.length; i++) {
			properties.put(keys[i], img.getProperty(keys[i]));
		}
	}
	final BufferedImage result = new BufferedImage(cm, raster,
		isAlphaPremultiplied, properties);
	img.copyData(raster);
	return result;
}
 
Example 3
Source File: FXGraphics2D.java    From SIMVA-SoS with Apache License 2.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 4
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Transform a rendered image in its array representation.
 * 
 * @param renderedImage the rendered image to transform.
 * @param bandNumber the the number of the band to consider..
 * @return the array holding the data.
 */
public static double[] renderedImage2DoubleArray( RenderedImage renderedImage, int bandNumber ) {
    int width = renderedImage.getWidth();
    int height = renderedImage.getHeight();

    double[] values = new double[width * height];
    RandomIter imageIter = RandomIterFactory.create(renderedImage, null);
    int index = 0;;
    for( int x = 0; x < width; x++ ) {
        for( int y = 0; y < height; y++ ) {
            double sample = imageIter.getSampleDouble(x, y, bandNumber);
            values[index++] = sample;
        }
    }
    imageIter.done();
    return values;
}
 
Example 5
Source File: ModelsEngine.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Takes a input raster and vectorializes it.
 *
 * @param input
 * @return
 */
public static double[] vectorizeDoubleMatrix( RenderedImage input ) {
    double[] U = new double[input.getWidth() * input.getHeight()];
    RandomIter inputRandomIter = RandomIterFactory.create(input, null);

    int j = 0;
    for( int i = 0; i < input.getHeight() * input.getWidth(); i = i + input.getWidth() ) {
        double tmp[] = new double[input.getWidth()];
        for( int k = 0; k < input.getWidth(); k++ ) {
            tmp[k] = inputRandomIter.getSampleDouble(k, j, 0);
        }

        System.arraycopy(tmp, 0, U, i, input.getWidth());
        j++;
    }

    return U;
}
 
Example 6
Source File: FXGraphics2D.java    From ccu-historian 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 7
Source File: PrintManager.java    From ganttproject with GNU General Public License v3.0 6 votes vote down vote up
public static void printChart(Chart chart, GanttExportSettings settings) {
  RenderedImage image = chart.getRenderedImage(settings);
  BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
  image.copyData(bufferedImage.getRaster());

  PrinterJob printJob = PrinterJob.getPrinterJob();

  printJob.setPrintable(new GanttPrintable(bufferedImage, GanttPrintable.REDUCE_FACTOR_DEFAULT));

  PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
  attr.add(MediaSizeName.ISO_A4);
  attr.add(OrientationRequested.LANDSCAPE);

  if (printJob.printDialog()) {
    try {
      printJob.print(attr);
    } catch (Exception e) {
      if (!GPLogger.log(e)) {
        e.printStackTrace(System.err);
      }
    }
  }
}
 
Example 8
Source File: CoverageUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Transform a double values rendered image in its integer array representation by scaling the values.
 * 
 * @param renderedImage the rendered image to transform.
 * @param multiply value by which to multiply the values before casting to integer.
 * @return the array holding the data.
 */
public static int[] renderedImage2IntegerArray( RenderedImage renderedImage, double multiply ) {
    int width = renderedImage.getWidth();
    int height = renderedImage.getHeight();

    int[] values = new int[width * height];
    RandomIter imageIter = RandomIterFactory.create(renderedImage, null);
    int index = 0;;
    for( int x = 0; x < width; x++ ) {
        for( int y = 0; y < height; y++ ) {
            double sample = imageIter.getSampleDouble(x, y, 0);
            sample = sample * multiply;
            values[index++] = (int) sample;
        }
    }
    imageIter.done();
    return values;
}
 
Example 9
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 10
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 11
Source File: ProjectionProfileOpImage.java    From pdfxtk with Apache License 2.0 5 votes vote down vote up
public ProjectionProfileOpImage(RenderedImage source,
	       Rectangle region) {
  super(source, new ROIShape(new Rectangle(source.getMinX(), source.getMinY(), 
			     source.getWidth(), source.getHeight())),
 source.getMinX(), source.getMinY(),
 1, 1);
  
  this.region = region;
  image = source;
  
  RasterFormatTag[] formatTags = getFormatTags();
  
  srcDRA = new DirectRasterAccessor(getData(), getColorModel());
}
 
Example 12
Source File: Utility.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Adjust the crop rectangle to fit within the image it is cropping. Also
 * ensure the area is square.
 *
 * @param image    The image being cropped
 * @param cropRect The rectangle defining the cropping area. This may be updated.
 */
public static void adjustRectToFitImage(RenderedImage image, Rectangle cropRect)
{
	// Make sure the rectangle is not too big
	if (cropRect.width > image.getWidth())
	{
		cropRect.width = image.getWidth();
	}
	if (cropRect.height > image.getHeight())
	{
		cropRect.height = image.getHeight();
	}

	// Make it square
	int dimension = Math.min(cropRect.width, cropRect.height);
	cropRect.setSize(dimension, dimension);

	// Now adjust the origin point so the box is within the image
	if ((cropRect.x + cropRect.width) > image.getWidth())
	{
		cropRect.x = image.getWidth() - cropRect.width;
	}
	if ((cropRect.y + cropRect.height) > image.getHeight())
	{
		cropRect.y = image.getHeight() - cropRect.height;
	}
}
 
Example 13
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 14
Source File: Utility.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Adjust the crop rectangle to fit within the image it is cropping. Also
 * ensure the area is square.
 *
 * @param image    The image being cropped
 * @param cropRect The rectangle defining the cropping area. This may be updated.
 */
public static void adjustRectToFitImage(RenderedImage image, Rectangle cropRect)
{
	// Make sure the rectangle is not too big
	if (cropRect.width > image.getWidth())
	{
		cropRect.width = image.getWidth();
	}
	if (cropRect.height > image.getHeight())
	{
		cropRect.height = image.getHeight();
	}

	// Make it square
	int dimension = Math.min(cropRect.width, cropRect.height);
	cropRect.setSize(dimension, dimension);

	// Now adjust the origin point so the box is within the image
	if ((cropRect.x + cropRect.width) > image.getWidth())
	{
		cropRect.x = image.getWidth() - cropRect.width;
	}
	if ((cropRect.y + cropRect.height) > image.getHeight())
	{
		cropRect.y = image.getHeight() - cropRect.height;
	}
}
 
Example 15
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 16
Source File: SunGraphics2D.java    From openjdk-8-source 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 17
Source File: S3HistogramEqualizerRIF.java    From DataHubSystem with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Compute the output equalized image. In contrary to the QL generation the
 * stretching can only performed on full dataset. So no operator can be 
 * provided to manage this operation by tile... 
 * 
 * @param paramBlock contains the RGB source image to produce the quicklook.
 * @param hints Optionally contains destination image layout.
 * @return the equalized image.
 * @throws IllegalArgumentException if source does not contains 3 bands.
 */
@SuppressWarnings ("unchecked")
public RenderedImage create(ParameterBlock paramBlock, RenderingHints hints)
{
   // One source supported 
   RenderedImage image = (RenderedImage)paramBlock.getSource(0);
   int num_bands=image.getSampleModel().getNumBands();
   Raster raster_data = image.getData();

   if (num_bands != 3) // Support only RGB bands :-(
   {
      throw new IllegalArgumentException (
         "S3 Equalization only support 3-banded RGB input image.");
   }

   int width = image.getWidth();
   int height = image.getHeight();

   List<int[]> histLUT;
   try
   {
      String equalizationFile = image instanceof QuicklookOlciOpImage ? 
         "olci-equalization.dat" : null;
      // could be loaded statically or inside constructor
      ObjectInputStream objectinputstream = new ObjectInputStream(
         getClass().getClassLoader().getResourceAsStream(equalizationFile));
      histLUT = (ArrayList<int[]>) objectinputstream.readObject();
   }
   catch (Exception e)
   {
      LOGGER.warn("Unable to load LUT for equalization. " +
         "Using a dynamic LUT " + e.getMessage());
      histLUT = histogramEqualizationLUT(raster_data);
   }

   BufferedImage histogramEQ = new BufferedImage(width, height,
      BufferedImage.TYPE_3BYTE_BGR);

   int red;
   int green;
   int blue;
   int new_pixel;

   for(int j=0; j<height; j++)
   {
      for(int i=0; i<width; i++)   
      {
         // Get pixels by R, G, B
         red   = getRed(raster_data, i, j);
         green = getGreen(raster_data, i, j);
         blue  = getBlue(raster_data, i, j);

         // Set new pixel values using the histogram lookup table
         if(red == 0 && green == 0 && blue == 0) continue;

         red = histLUT.get(0)[red];
         green = histLUT.get(1)[green];
         blue = histLUT.get(2)[blue];

         // Return back to original format
         new_pixel = new Color(
            red*255/Common.colorRange, 
            green*255/Common.colorRange,
            blue*255/Common.colorRange).getRGB();

         // Write pixels into image
         histogramEQ.setRGB(i, j, new_pixel);
      }
   }
   return histogramEQ;
}
 
Example 18
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 19
Source File: SunGraphics2D.java    From dragonwell8_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 20
Source File: PixelInfoViewUtils.java    From snap-desktop with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Check if the (x,y) pixel coordinates are within the raster bounds
 *
 * @param raster the current raster
 * @param x      the pixel x in the raster resolution
 * @param y      the pixel y in the raster resolution
 * @return true if the pixel (x,y) belongs to the raster bounds, false otherwise
 */
private static boolean coordinatesAreInRasterBounds(final RasterDataNode raster, final int x, final int y) {
    final RenderedImage levelImage = raster.getSourceImage().getImage(0);
    return x >= 0 && y >= 0 && x < levelImage.getWidth() && y < levelImage.getHeight();
}