/** * Crops the image representing a full tile set to the required dimension and returns it, but * keeps minx and miny being zero. * * @param fullTilesRaster * @param tiledImageGridRange * @param cropTo * @return */ private RenderedImage cropToRequiredDimension( final RenderedImage fullTilesRaster, final GridEnvelope cropTo) { GridEnvelope2D crop = new GridEnvelope2D( cropTo.getLow(0), cropTo.getLow(1), cropTo.getSpan(0), cropTo.getSpan(1)); GridEnvelope2D origDim = new GridEnvelope2D( fullTilesRaster.getMinX(), fullTilesRaster.getMinY(), fullTilesRaster.getWidth(), fullTilesRaster.getHeight()); if (!origDim.contains(crop)) { throw new IllegalArgumentException( "Original image (" + origDim + ") does not contain desired dimension (" + crop + ")"); } else if (origDim.equals(crop)) { if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer( "No need to crop image, full tiled dimension and target one " + "do match: original: " + fullTilesRaster.getWidth() + "x" + fullTilesRaster.getHeight() + ", target: " + crop.getSpan(0) + "x" + crop.getSpan(1)); } return fullTilesRaster; } ParameterBlock cropParams = new ParameterBlock(); cropParams.addSource(fullTilesRaster); // Source // cropParams.add(Float.valueOf(cropTo.x - tiledImageGridRange.x)); // x origin for each // band // cropParams.add(Float.valueOf(cropTo.y - tiledImageGridRange.y)); // y origin for each // band cropParams.add(Float.valueOf(crop.getLow(0))); // x origin for each band cropParams.add(Float.valueOf(crop.getLow(1))); // y origin for each band cropParams.add(Float.valueOf(crop.getSpan(0))); // width for each band cropParams.add(Float.valueOf(crop.getSpan(1))); // height for each band final RenderingHints hints = new RenderingHints(JAI.KEY_OPERATION_BOUND, OpImage.OP_NETWORK_BOUND); RenderedImage image = JAI.create("Crop", cropParams, hints); // assert cropTo.x - tiledImageGridRange.x == image.getMinX(); // assert cropTo.y - tiledImageGridRange.y == image.getMinY(); assert crop.getLow(0) == image.getMinX(); assert crop.getLow(1) == image.getMinY(); assert crop.getSpan(0) == image.getWidth(); assert crop.getSpan(1) == image.getHeight(); // assert cropTo.x == image.getMinX(); // assert cropTo.y == image.getMinY(); // assert cropTo.width == image.getWidth(); // assert cropTo.height == image.getHeight(); return image; }
@Test public void testDataTypes() throws IOException, FileNotFoundException { if (!isGDALAvailable) { return; } final List<String> fileList = new ArrayList<String>(4); fileList.add("paletted.tif"); fileList.add("utmByte.tif"); fileList.add("utmInt16.tif"); fileList.add("utmInt32.tif"); fileList.add("utmFloat32.tif"); fileList.add("utmFloat64.tif"); for (String fileName : fileList) { final ImageReadParam irp = new ImageReadParam(); final File inputFile = TestData.file(this, fileName); irp.setSourceSubsampling(1, 1, 0, 0); ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance(); reader.setInput(inputFile); final RenderedImage image = reader.readAsRenderedImage(0, irp); if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image, fileName); if (!fileName.contains("paletted")) { Assert.assertEquals(256, image.getHeight()); Assert.assertEquals(256, image.getWidth()); } else { Assert.assertEquals(128, image.getHeight()); Assert.assertEquals(128, image.getWidth()); } reader.dispose(); } }
public static RenderedImage createRenderedImage(RenderedImage image, Color bkg) { if (bkg == null) return image; BufferedImage bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); g.setBackground(bkg); g.clearRect(0, 0, image.getWidth(), image.getHeight()); g.drawRenderedImage(image, new AffineTransform()); return bufferedImage; }
public void appendLoggingGeometries(String geomName, RenderedImage img) { if (LOGGER.isLoggable(GEOM_LEVEL)) { appendLoggingGeometries( geomName, new GridEnvelope2D(img.getMinX(), img.getMinY(), img.getWidth(), img.getHeight())); } }
@Override public void process() throws Exception { RenderedImage source = (RenderedImage) params.get(INPUT_IMG); RenderedImage result = source; Rectangle area = (Rectangle) params.get(P_AREA); if (area == null) { LOGGER.warn("Cannot apply \"{}\" because a parameter is null", OP_NAME); // $NON-NLS-1$ } else { area = area.intersection( new Rectangle( source.getMinX(), source.getMinY(), source.getWidth(), source.getHeight())); if (area.width > 1 && area.height > 1) { ParameterBlock pb = new ParameterBlock(); pb.addSource(source); pb.add((float) area.x).add((float) area.y); pb.add((float) area.width).add((float) area.height); result = JAI.create("crop", pb, null); // $NON-NLS-1$ if (JMVUtils.getNULLtoFalse(params.get(P_SHIFT_TO_ORIGIN))) { float diffw = source.getMinX() - result.getMinX(); float diffh = source.getMinY() - result.getMinY(); if (diffw != 0.0f || diffh != 0.0f) { pb = new ParameterBlock(); pb.addSource(result); pb.add(diffw); pb.add(diffh); result = JAI.create("translate", pb, null); // $NON-NLS-1$ } } } } params.put(OUTPUT_IMG, result); }
private RenderedOp createScaledImage( RenderedImage sourceImage, S2Resolution resolution, int level) { int sourceWidth = sourceImage.getWidth(); int sourceHeight = sourceImage.getHeight(); int targetWidth = imageLayouts[0].width >> level; int targetHeight = imageLayouts[0].height >> level; float scaleX = (float) targetWidth / (float) sourceWidth; float scaleY = (float) targetHeight / (float) sourceHeight; float corrFactorX = resolution == S2Resolution.R20M ? R20M_X_FACTOR : R60M_X_FACTOR; float corrFactorY = resolution == S2Resolution.R20M ? R20M_Y_FACTOR : R60M_Y_FACTOR; final Dimension tileDim = getTileDim(targetWidth, targetHeight); ImageLayout imageLayout = new ImageLayout(); imageLayout.setTileWidth(tileDim.width); imageLayout.setTileHeight(tileDim.height); RenderingHints renderingHints = new RenderingHints( JAI.KEY_BORDER_EXTENDER, BorderExtender.createInstance(BorderExtender.BORDER_ZERO)); renderingHints.put(JAI.KEY_IMAGE_LAYOUT, imageLayout); RenderedOp scaledImage = ScaleDescriptor.create( sourceImage, scaleX * corrFactorX, scaleY * corrFactorY, 0F, 0F, Interpolation.getInstance(Interpolation.INTERP_NEAREST), renderingHints); if (scaledImage.getWidth() != targetWidth || scaledImage.getHeight() != targetHeight) { return CropDescriptor.create( scaledImage, 0.0F, 0.0F, (float) targetWidth, (float) targetHeight, null); } else { return scaledImage; } }
/** This template method should set the xlink:href attribute on the input Element parameter */ protected void handleHREF( RenderedImage image, Element imageElement, SVGGeneratorContext generatorContext) throws SVGGraphics2DIOException { // // Create an buffered image if necessary // BufferedImage buf = null; if (image instanceof BufferedImage && ((BufferedImage) image).getType() == getBufferedImageType()) { buf = (BufferedImage) image; } else { Dimension size = new Dimension(image.getWidth(), image.getHeight()); buf = buildBufferedImage(size); Graphics2D g = createGraphics(buf); g.drawRenderedImage(image, IDENTITY); g.dispose(); } // // Cache image and set xlink:href // cacheBufferedImage(imageElement, buf, generatorContext); }
protected void printImage(RenderedImage renderedImage) { SampleModel sampleModel = renderedImage.getSampleModel(); int height = renderedImage.getHeight(); int width = renderedImage.getWidth(); int numOfBands = sampleModel.getNumBands(); int[] pixels = new int[height * width * numOfBands]; Raster raster = renderedImage.getData(); raster.getPixels(0, 0, width, height, pixels); int offset = 0; for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { offset = (h * width * numOfBands) + (w * numOfBands); System.out.print("[" + w + ", " + h + "] = "); for (int b = 0; b < numOfBands; b++) { System.out.print(pixels[offset + b] + " "); } } System.out.println(); } }
/** * Constructs a <code>SubsampleBinaryToGrayOpImage</code> from a <code>RenderedImage</code> * source, x and y scale object. The image dimensions are determined by forward-mapping the source * bounds, and are passed to the superclass constructor by means of the <code>layout</code> * parameter. Other fields of the layout are passed through unchanged. If <code>layout</code> is * <code>null</code>, a new <code>ImageLayout</code> will be constructor to hold the bounds * information. * * <p>The float rounding errors, such as 1.2 being internally represented as 1.200001, are dealt * with the floatTol, which is set up so that only 1/10 of pixel error will occur at the end of a * line, which yields correct results with Math.round() operation. The repeatability is guaranteed * with a one-time computed table xvalues and yvalues. * * @param layout an <code>ImageLayout</code> optionally containing the tile grid layout, <code> * SampleModel</code>, and <code>ColorModel</code>, or <code>null</code>. * @param source a <code>RenderedImage</code>. from this <code>OpImage</code>, or <code>null * </code>. If <code>null</code>, no caching will be performed. * @param cobbleSources a boolean indicating whether <code>computeRect</code> expects contiguous * sources. * @param extender a <code>BorderExtender</code>, or <code>null</code>. * @param interp an <code>Interpolation</code> object to use for resampling. * @param scaleX scale factor along x axis. * @param scaleY scale factor along y axis. * @throws IllegalArgumentException if combining the source bounds with the layout parameter * results in negative output width or height. */ public SubsampleBinaryToGrayOpImage( RenderedImage source, ImageLayout layout, Map config, float scaleX, float scaleY) { super( vectorize(source), layoutHelper(source, scaleX, scaleY, layout, config), configHelper(config), true, // cobbleSources, null, // extender null, // interpolation null); this.scaleX = scaleX; this.scaleY = scaleY; int srcMinX = source.getMinX(); int srcMinY = source.getMinY(); int srcWidth = source.getWidth(); int srcHeight = source.getHeight(); // compute floatTol, invScaleX, blockX, dWidth, dHeight,... computeDestInfo(srcWidth, srcHeight); if (extender == null) { computableBounds = new Rectangle(0, 0, dWidth, dHeight); } else { // If extender is present we can write the entire destination. computableBounds = getBounds(); } // these can be delayed, such as placed in computeRect() buildLookupTables(); // compute the begining bit position of each row and column computeXYValues(srcWidth, srcHeight, srcMinX, srcMinY); }
/** * Loads an image from a URL * * @param bitmapFile the bitmap file * @return the bitmap as BufferedImage */ public static BufferedImage getImage(File bitmapFile) { try { InputStream in = new java.io.FileInputStream(bitmapFile); try { in = new java.io.BufferedInputStream(in); ImageTagRegistry reg = ImageTagRegistry.getRegistry(); Filter filt = reg.readStream(in); if (filt == null) { return null; } RenderedImage red = filt.createDefaultRendering(); if (red == null) { return null; } BufferedImage img = new BufferedImage(red.getWidth(), red.getHeight(), BufferedImage.TYPE_INT_ARGB); red.copyData(img.getRaster()); return img; } finally { IOUtils.closeQuietly(in); } } catch (IOException e) { return null; } }
public RenderedImage scale(RenderedImage renderedImage, int width) { if (width <= 0) { return renderedImage; } int imageHeight = renderedImage.getHeight(); int imageWidth = renderedImage.getWidth(); double factor = (double) width / imageWidth; int scaledHeight = (int) (factor * imageHeight); int scaledWidth = width; BufferedImage bufferedImage = getBufferedImage(renderedImage); int type = bufferedImage.getType(); if (type == 0) { type = BufferedImage.TYPE_INT_ARGB; } BufferedImage scaledBufferedImage = new BufferedImage(scaledWidth, scaledHeight, type); Graphics graphics = scaledBufferedImage.getGraphics(); Image scaledImage = bufferedImage.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH); graphics.drawImage(scaledImage, 0, 0, null); return scaledBufferedImage; }
/** * Constructs a <code>SubsampleBinaryToGray4x4OpImage</code> from a <code>RenderedImage</code> * source, an optional <code>BorderExtender</code>, x and y scale and translation factors, and an * <code>Interpolation</code> object. The image dimensions are determined by forward-mapping the * source bounds, and are passed to the superclass constructor by means of the <code>layout</code> * parameter. Other fields of the layout are passed through unchanged. If <code>layout</code> is * <code>null</code>, a new <code>ImageLayout</code> will be constructor to hold the bounds * information. * * <p>Note that the scale factors are represented internally as Rational numbers in order to * workaround inexact device specific representation of floating point numbers. For instance the * floating point number 1.2 is internally represented as 1.200001, which can throw the * calculations off during a forward/backward map. * * <p>The Rational approximation is valid upto the sixth decimal place. * * @param layout an <code>ImageLayout</code> optionally containing the tile grid layout, <code> * SampleModel</code>, and <code>ColorModel</code>, or <code>null</code>. * @param source a <code>RenderedImage</code>. * <p>from this <code>OpImage</code>, or <code>null</code>. If <code>null</code>, no caching * will be performed. * @param cobbleSources a boolean indicating whether <code>computeRect</code> expects contiguous * sources. * @param extender a <code>BorderExtender</code>, or <code>null</code>. * @param interp an <code>Interpolation</code> object to use for resampling. * @param scaleX scale factor along x axis. * @param scaleY scale factor along y axis. * @throws IllegalArgumentException if combining the source bounds with the layout parameter * results in negative output width or height. */ public SubsampleBinaryToGray4x4OpImage(RenderedImage source, ImageLayout layout, Map config) { super( vectorize(source), SubsampleBinaryToGrayOpImage.layoutHelper(source, 1.0F / 4, 1.0F / 4, layout, config), config, true, // cobbleSources, null, // extender null, // interpolation null); int srcWidth = source.getWidth(); int srcHeight = source.getHeight(); blockX = blockY = 4; dWidth = srcWidth / blockX; dHeight = srcHeight / blockY; if (extender == null) { computableBounds = new Rectangle(0, 0, dWidth, dHeight); } else { // If extender is present we can write the entire destination. computableBounds = getBounds(); } // these can be delayed, such as placed in computeRect() buildLookupTables(); // compute the begining bit position of each row and column computeXYValues(dWidth, dHeight); }
/** A wrapper for {@link #setImage(int, int, ByteBuffer, Rectangle, int)}. */ private void setImage(RenderedImage image, Rectangle rect) throws IOException { setImage( image.getWidth(), image.getHeight(), ImageIOHelper.getImageByteBuffer(image), rect, image.getColorModel().getPixelSize()); }
public static RenderedOp transformImage( RenderedImage image, double x0, double y0, double theta, double scale) { final AffineTransform transform = new AffineTransform(); transform.rotate(theta, -0.5f * image.getWidth(), -0.5f * image.getHeight()); transform.scale(scale, scale); transform.translate(x0, y0); return transformImage(image, transform); }
// package accessible for SubsampleBinaryToGrayOpImage4x4, etc... static ImageLayout layoutHelper( RenderedImage source, float scaleX, float scaleY, ImageLayout il, Map config) { ImageLayout layout = (il == null) ? new ImageLayout() : (ImageLayout) il.clone(); // to compute dWidth and dHeight // fTol and dWi, dHi must be the same as in computeDestInfo(..) // due to static method, a few lines of coding are repeated int srcWidth = source.getWidth(); int srcHeight = source.getHeight(); float f_dw = scaleX * srcWidth; float f_dh = scaleY * srcHeight; float fTol = .1F * Math.min(scaleX / (f_dw + 1.0F), scaleY / (f_dh + 1.0F)); int dWi = (int) (f_dw); int dHi = (int) (f_dh); // let it be int in the almost int case // espacially in the true int case with float calculation errors if (Math.abs(Math.round(f_dw) - f_dw) < fTol) { dWi = Math.round(f_dw); } if (Math.abs(Math.round(f_dh) - f_dh) < fTol) { dHi = Math.round(f_dh); } // Set the top left coordinate of the destination layout.setMinX((int) (scaleX * source.getMinX())); layout.setMinY((int) (scaleY * source.getMinY())); layout.setWidth(dWi); layout.setHeight(dHi); // sample model SampleModel sm = layout.getSampleModel(null); if (sm == null || sm.getDataType() != DataBuffer.TYPE_BYTE || !(sm instanceof PixelInterleavedSampleModel || sm instanceof SinglePixelPackedSampleModel && sm.getNumBands() == 1)) { // Width and height will be corrected in OpImage.layoutHelper sm = new PixelInterleavedSampleModel(DataBuffer.TYPE_BYTE, 1, 1, 1, 1, new int[] {0}); } layout.setSampleModel(sm); ColorModel cm = layout.getColorModel(null); if (cm == null || !JDKWorkarounds.areCompatibleDataModels(sm, cm)) { layout.setColorModel(ImageUtil.getCompatibleColorModel(sm, config)); } return layout; }
/** * The constructor of the class, which creates the arrays and instances needed to obtain the image * data and registers the class to listen to mouse motion events. * * @param image a RenderedImage for display */ public DisplayJAIWhileStoringCoordinates(RenderedImage image) { super(image); // calls the constructor for DisplayJAI. readIterator = RandomIterFactory.create(image, null); // creates the iterator. // Get some data about the image width = image.getWidth(); height = image.getHeight(); int dataType = image.getSampleModel().getDataType(); // gets the data type switch (dataType) { case DataBuffer.TYPE_BYTE: case DataBuffer.TYPE_SHORT: case DataBuffer.TYPE_USHORT: case DataBuffer.TYPE_INT: isDoubleType = false; break; case DataBuffer.TYPE_FLOAT: case DataBuffer.TYPE_DOUBLE: isDoubleType = true; break; } // Depending on the image data type, allocate the double or the int array. if (isDoubleType) dpixel = new double[image.getSampleModel().getNumBands()]; else ipixel = new int[image.getSampleModel().getNumBands()]; // Is the image color model indexed ? isIndexed = (image.getColorModel() instanceof IndexColorModel); if (isIndexed) { // Retrieve the index color model of the image. IndexColorModel icm = (IndexColorModel) image.getColorModel(); // Get the number of elements in each band of the colormap. int mapSize = icm.getMapSize(); // Allocate an array for the lookup table data. byte[][] templutData = new byte[3][mapSize]; // Load the lookup table data from the IndexColorModel. icm.getReds(templutData[0]); icm.getGreens(templutData[1]); icm.getBlues(templutData[2]); // Load the lookup table data into a short array to avoid negative numbers. lutData = new short[3][mapSize]; for (int entry = 0; entry < mapSize; entry++) { lutData[0][entry] = templutData[0][entry] > 0 ? templutData[0][entry] : (short) (templutData[0][entry] + 256); lutData[1][entry] = templutData[1][entry] > 0 ? templutData[1][entry] : (short) (templutData[1][entry] + 256); lutData[2][entry] = templutData[2][entry] > 0 ? templutData[2][entry] : (short) (templutData[2][entry] + 256); } } // end if indexed // Registers the mouse listener. addMouseListener(this); // Create the list of coordinates clicksInformation = new ArrayList(); }
public void setImage(RenderedImage im) { image = im; Dimension size = new Dimension(im.getWidth(), im.getHeight()); int xOffset = (int) (size.getWidth() * .1); int yOffset = (int) (size.getHeight() * .1); testPoint[0] = new Point(xOffset, yOffset); testPoint[1] = new Point((int) size.getWidth() - xOffset, yOffset); testPoint[2] = new Point((int) size.getWidth() - xOffset, (int) size.getHeight() - yOffset); testPoint[3] = new Point(xOffset, (int) size.getHeight() - yOffset); repaint(); }
/** Gets the number of tiles */ public int getNumTiles() { Rectangle sourceRegion = getSourceRegion(); if (sourceRegion == null) { if (imgsrc != null) sourceRegion = new Rectangle( imgsrc.getMinX(), imgsrc.getMinY(), imgsrc.getWidth(), imgsrc.getHeight()); else sourceRegion = raster.getBounds(); } else { if (imgsrc != null) sourceRegion = sourceRegion.intersection( new Rectangle( imgsrc.getMinX(), imgsrc.getMinY(), imgsrc.getWidth(), imgsrc.getHeight())); else sourceRegion = sourceRegion.intersection(raster.getBounds()); } int scaleX = getSourceXSubsampling(); int scaleY = getSourceYSubsampling(); int xOffset = getSubsamplingXOffset(); int yOffset = getSubsamplingYOffset(); int w = (sourceRegion.width - xOffset + scaleX - 1) / scaleX; int h = (sourceRegion.height - yOffset + scaleY - 1) / scaleY; minX = (sourceRegion.x + xOffset) / scaleX; minY = (sourceRegion.y + yOffset) / scaleY; numTiles = (int) ((Math.floor((minX + w + tileWidth - 1.0) / tileWidth) - Math.floor((double) minX / tileWidth)) * (Math.floor((minY + h + tileHeight - 1.0) / tileHeight) - Math.floor((double) minY / tileHeight))); tileGridXOffset += (minX - tileGridXOffset) / tileWidth * tileWidth; tileGridYOffset += (minY - tileGridYOffset) / tileHeight * tileHeight; return numTiles; }
/** * Set the image value in the given writable field to the new image defined by a set of pixels. * * <p> * * @param imgIndex The index of the image in the array * @param img The new image to use as the source */ public void setImage(int imgIndex, RenderedImage img) throws InvalidOperationTimingException, InvalidFieldValueException, InvalidWritableFieldException, InvalidFieldException { if (imgIndex < 0) throw new ArrayIndexOutOfBoundsException(); checkWriteAccess(); synchronized (theEventQueue.eventLock) { MFImageWrapper queuedElement = (MFImageWrapper) theEventQueue.getLast(this); if (queuedElement == null || !queuedElement.isSetOneValue) { // Input and output buffers do not mix if (!storedInput && !storedOutput) { // Avoid clogging this buffer if // index out of bounds if (imgIndex < 0) throw new ArrayIndexOutOfBoundsException(); loadInputValue(); if (imgIndex >= storedInputValue.length) throw new ArrayIndexOutOfBoundsException(); queuedElement = this; loadInputValue(); isSetOneValue = true; } else { // If this generates an ArrayIndexOutOfBounds its okay, // the element will be garbage. queuedElement = new MFImageWrapper(theNode, fieldIndex, theEventQueue, theEventAdapterFactory, true); queuedElement.isSetOneValue = true; } queuedElement.rewriteImageToSize(imgIndex, img.getWidth(), img.getHeight()); SFImageUtils.convertRenderedImageToData( img, queuedElement.storedInputValue, queuedElement.findStartOfInputImage(imgIndex)); theEventQueue.processEvent(queuedElement); } else { checkDataSanity(); queuedElement.rewriteImageToSize(imgIndex, img.getWidth(), img.getHeight()); SFImageUtils.convertRenderedImageToData( img, queuedElement.storedInputValue, queuedElement.findStartOfInputImage(imgIndex)); queuedElement.getSize(); } } }
public ImageHeader(RenderedImage image, String tileFormat) { this( new ImageLayout( image.getMinX(), image.getMinY(), image.getWidth(), image.getHeight(), image.getTileGridXOffset(), image.getTileGridYOffset(), image.getTileWidth(), image.getTileHeight(), image.getSampleModel(), image.getColorModel()), tileFormat); }
// called from outer class to rescale the image public void reScale(double scaleFactor) { if (image == null) { return; } if (scaleFactor != 0) { scale = scaleFactor; } setPreferredSize( new Dimension( (int) (image.getWidth() * dependentScale * scale), (int) (image.getHeight() * dependentScale * scale))); repaint(); if (scrollPane != null) scrollPane.revalidate(); else revalidate(); }
public static ImageData createImageData(RenderedImage image) { ImageData swtdata = null; int width = image.getWidth(); int height = image.getHeight(); PaletteData palette; int depth; depth = 24; palette = new PaletteData(0xFF0000, 0xFF00, 0xFF); swtdata = new ImageData(width, height, depth, palette); swtdata.transparentPixel = TRANSPARENT; byte blueT = (byte) ((TRANSPARENT) & 0xFF); byte greenT = (byte) ((TRANSPARENT >> 8) & 0xFF); byte redT = (byte) ((TRANSPARENT >> 16) & 0xFF); // System.out.println("red="+redT+"blue"+blueT+"green"+greenT); // System.out.println("Transparent"+TRANSPARENT); // awtImage2.getRGB(); Raster raster = image.getData(); int[] awtdata = raster.getPixels( 0, 0, width, height, new int[width * height * 3]); // raster.getNumBands()]); int step = swtdata.depth / 8; byte[] data = swtdata.data; int baseindex = 0; // System.out.println( "AWT size:" + awtdata.length ); for (int y = 0; y < height; y++) { int idx = ((0 + y) * swtdata.bytesPerLine) + (0 * step); for (int x = 0; x < width; x++) { baseindex = (x + (y * width)) * 4; if (awtdata[baseindex + 3] == 0) { data[idx++] = blueT; data[idx++] = greenT; data[idx++] = redT; } else { data[idx++] = (byte) awtdata[baseindex]; data[idx++] = (byte) awtdata[baseindex + 1]; data[idx++] = (byte) awtdata[baseindex + 2]; } } } return swtdata; }
private byte[] getROIData(ROI roi, Rectangle rectIMG) { byte[] dataROI; PlanarImage roiIMG = roi.getAsImage(); Rectangle rectROI = roiIMG.getBounds(); // Forcing to component colormodel in order to avoid packed bits ImageWorker w = new ImageWorker(); w.setImage(roiIMG); w.forceComponentColorModel(); RenderedImage img = w.getRenderedImage(); // BufferedImage test = new BufferedImage(rectIMG.width, rectIMG.height, BufferedImage.TYPE_BYTE_GRAY); ImageLayout2 layout = new ImageLayout2(test); layout.setMinX(img.getMinX()); layout.setMinY(img.getMinY()); layout.setWidth(img.getWidth()); layout.setHeight(img.getHeight()); // Lookup byte[] lut = new byte[256]; lut[255] = 1; lut[1] = 1; LookupTableJAI table = new LookupTableJAI(lut); RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout); RenderedOp transformed = LookupDescriptor.create(img, table, hints); Graphics2D gc2d = null; // Translation parameters in order to position the ROI data correctly in the Raster Space int trX = -rectIMG.x + rectROI.x - rectIMG.x; int trY = -rectIMG.y + rectROI.y - rectIMG.y; try { gc2d = test.createGraphics(); gc2d.drawRenderedImage(transformed, AffineTransform.getTranslateInstance(trX, trY)); } finally { gc2d.dispose(); } Rectangle testRect = new Rectangle(rectIMG.width, rectIMG.height); DataBufferByte dbRoi = (DataBufferByte) test.getData(testRect).getDataBuffer(); dataROI = dbRoi.getData(); // BufferedImage is stored in memory so the planarImage chain before can be disposed ImageUtilities.disposePlanarImageChain(transformed); // Flush of the BufferedImage test.flush(); return dataROI; }
/** * Loads an image from a URL * * @param url the URL to the image * @return the bitmap as BufferedImage TODO This method doesn't close the InputStream opened by * the URL. */ public static BufferedImage getImage(URL url) { ImageTagRegistry reg = ImageTagRegistry.getRegistry(); Filter filt = reg.readURL(new ParsedURL(url)); if (filt == null) { return null; } RenderedImage red = filt.createDefaultRendering(); if (red == null) { return null; } BufferedImage img = new BufferedImage(red.getWidth(), red.getHeight(), BufferedImage.TYPE_INT_ARGB); red.copyData(img.getRaster()); return img; }
/** * Test Read without exploiting JAI-ImageIO Tools * * @throws FileNotFoundException * @throws IOException */ @Test public void manualRead() throws IOException, FileNotFoundException { if (!isGDALAvailable) { return; } final ImageReadParam irp = new ImageReadParam(); // Reading a simple GrayScale image String fileName = "utmByte.tif"; final File inputFile = TestData.file(this, fileName); irp.setSourceSubsampling(2, 2, 0, 0); ImageReader reader = new GeoTiffImageReaderSpi().createReaderInstance(); reader.setInput(inputFile); final RenderedImage image = reader.readAsRenderedImage(0, irp); if (TestData.isInteractiveTest()) Viewer.visualizeAllInformation(image, fileName); Assert.assertEquals(128, image.getWidth()); Assert.assertEquals(128, image.getHeight()); reader.dispose(); }
protected Image getImage(InputStream is, byte[] bytes) throws PortalException, SystemException { try { if (is != null) { bytes = FileUtil.getBytes(is); } ImageBag imageBag = ImageProcessorUtil.read(bytes); RenderedImage renderedImage = imageBag.getRenderedImage(); String type = imageBag.getType(); if (renderedImage == null) { throw new ImageTypeException(); } int height = renderedImage.getHeight(); int width = renderedImage.getWidth(); int size = bytes.length; Image image = new ImageImpl(); image.setTextObj(bytes); image.setType(type); image.setHeight(height); image.setWidth(width); image.setSize(size); return image; } catch (IOException ioe) { throw new SystemException(ioe); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { if (_log.isWarnEnabled()) { _log.warn(ioe); } } } } }
/** * 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; }
/** The handler sets the xlink:href tag and returns a transform */ public AffineTransform handleImage( RenderedImage image, Element imageElement, int x, int y, int width, int height, SVGGeneratorContext generatorContext) { int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); AffineTransform af = null; if (imageWidth == 0 || imageHeight == 0 || width == 0 || height == 0) { // Forget about it handleEmptyImage(imageElement); } else { // First set the href try { handleHREF(image, imageElement, generatorContext); } catch (SVGGraphics2DIOException e) { try { generatorContext.errorHandler.handleError(e); } catch (SVGGraphics2DIOException io) { // we need a runtime exception because // java.awt.Graphics2D method doesn't throw exceptions.. throw new SVGGraphics2DRuntimeException(io); } } // Then create the transformation: // Because we cache image data, the stored image may // need to be scaled. af = handleTransform( imageElement, x, y, imageWidth, imageHeight, width, height, generatorContext); } return af; }
private BufferedImage cropScaleGrayscale(Rectangle visibleRect, RenderedImage image) { int minX = image.getMinX(); int minY = image.getMinY(); int width = image.getWidth(); int height = image.getHeight(); Rectangle bounds = new Rectangle(minX, minY, width, height); visibleRect = bounds.intersection(visibleRect); if (bounds.contains(visibleRect)) { ParameterBlock pb = new ParameterBlock(); pb.addSource(image); pb.add((float) visibleRect.x); pb.add((float) visibleRect.y); pb.add((float) visibleRect.width); pb.add((float) visibleRect.height); image = JAI.create("Crop", pb, JAIContext.noCacheHint); } Dimension previewSize = getSize(); if ((visibleRect.width > previewSize.width) || (visibleRect.height > previewSize.height)) { float scale = Math.min( previewSize.width / (float) visibleRect.width, previewSize.height / (float) visibleRect.height); image = ConvolveDescriptor.create(image, Functions.getGaussKernel(.25 / scale), null); ParameterBlock pb = new ParameterBlock(); pb.addSource(image); pb.add(scale); pb.add(scale); image = JAI.create("Scale", pb, JAIContext.noCacheHint); } image = Functions.toColorSpace(image, JAIContext.systemColorSpace, null); if (image.getSampleModel().getDataType() == DataBuffer.TYPE_USHORT) { image = Functions.fromUShortToByte(image, null); } return Functions.toFastBufferedImage(image); }
/** * Returns a contiguous <code>Raster</code> of data over the specified <code>Rectangle</code>. If * the region is a sub-region of a single tile, then a child of that tile will be returned. If the * region overlaps more than one tile and has 8 bits per sample, then a pixel interleaved Raster * having band offsets 0,1,... will be returned. Otherwise the Raster returned by <code> * im.copyData(null)</code> will be returned. */ private static final Raster getContiguousData(RenderedImage im, Rectangle region) { if (im == null) { throw new IllegalArgumentException("im == null"); } else if (region == null) { throw new IllegalArgumentException("region == null"); } Raster raster; if (im.getNumXTiles() == 1 && im.getNumYTiles() == 1) { // Image is not tiled so just get a reference to the tile. raster = im.getTile(im.getMinTileX(), im.getMinTileY()); // Ensure result has requested coverage. Rectangle bounds = raster.getBounds(); if (!bounds.equals(region)) { raster = raster.createChild( region.x, region.y, region.width, region.height, region.x, region.y, null); } } else { // Image is tiled. // Create an interleaved raster for copying for 8-bit case. // This ensures that for RGB data the band offsets are {0,1,2}. SampleModel sampleModel = im.getSampleModel(); WritableRaster target = sampleModel.getSampleSize(0) == 8 ? Raster.createInterleavedRaster( DataBuffer.TYPE_BYTE, im.getWidth(), im.getHeight(), sampleModel.getNumBands(), new Point(im.getMinX(), im.getMinY())) : null; // Copy the data. raster = im.copyData(target); } return raster; }