List of usage examples for java.awt.image RenderedImage getColorModel
ColorModel getColorModel();
From source file:org.geoserver.wps.gs.GeorectifyCoverage.java
@DescribeResults({ @DescribeResult(name = "result", description = "Georectified raster", type = GridCoverage2D.class), @DescribeResult(name = "path", description = "Pathname of the generated raster on the server", type = String.class) }) public Map<String, Object> execute( @DescribeParameter(name = "data", description = "Input raster") GridCoverage2D coverage, @DescribeParameter(name = "gcp", description = "List of Ground control points. Points are specified as [x,y] or [x,y,z].") String gcps, @DescribeParameter(name = "bbox", description = "Bounding box for output", min = 0) Envelope bbox, @DescribeParameter(name = "targetCRS", description = "Coordinate reference system to use for the output raster") CoordinateReferenceSystem crs, @DescribeParameter(name = "width", description = "Width of output raster in pixels", min = 0) Integer width, @DescribeParameter(name = "height", description = "Height of output raster in pixels", min = 0) Integer height, @DescribeParameter(name = "warpOrder", min = 0, description = "Order of the warping polynomial (1 to 3)") Integer warpOrder, @DescribeParameter(name = "transparent", min = 0, description = "Force output to have transparent background") Boolean transparent, @DescribeParameter(name = "store", min = 0, description = "Indicates whether to keep the output file after processing") Boolean store, @DescribeParameter(name = "outputPath", min = 0, description = "Pathname where the output file is stored") String outputPath) throws IOException { GeoTiffReader reader = null;/*w ww .java 2s . co m*/ List<File> removeFiles = new ArrayList<File>(); String location = null; try { File tempFolder = config.getTempFolder(); File loggingFolder = config.getLoggingFolder(); // do we have to add the alpha channel? boolean forceTransparent = false; if (transparent == null) { transparent = true; } ColorModel cm = coverage.getRenderedImage().getColorModel(); if (cm.getTransparency() == Transparency.OPAQUE && transparent) { forceTransparent = true; } // // // // STEP 1: Getting the dataset to be georectified // // // final Object fileSource = coverage.getProperty(GridCoverage2DReader.FILE_SOURCE_PROPERTY); if (fileSource != null && fileSource instanceof String) { location = (String) fileSource; } if (location == null) { RenderedImage image = coverage.getRenderedImage(); if (forceTransparent) { ImageWorker iw = new ImageWorker(image); iw.forceComponentColorModel(); final ImageLayout tempLayout = new ImageLayout(image); tempLayout.unsetValid(ImageLayout.COLOR_MODEL_MASK).unsetValid(ImageLayout.SAMPLE_MODEL_MASK); RenderedImage alpha = ConstantDescriptor.create(Float.valueOf(image.getWidth()), Float.valueOf(image.getHeight()), new Byte[] { Byte.valueOf((byte) 255) }, new RenderingHints(JAI.KEY_IMAGE_LAYOUT, tempLayout)); iw.addBand(alpha, false); image = iw.getRenderedImage(); cm = image.getColorModel(); } File storedImageFile = storeImage(image, tempFolder); location = storedImageFile.getAbsolutePath(); removeFiles.add(storedImageFile); } // // // // STEP 2: Adding Ground Control Points // // // final int gcpNum[] = new int[1]; final String gcp = parseGcps(gcps, gcpNum); File vrtFile = addGroundControlPoints(location, gcp, config.getGdalTranslateParameters()); if (vrtFile == null || !vrtFile.exists() || !vrtFile.canRead()) { throw new IOException("Unable to get a valid file with attached Ground Control Points"); } removeFiles.add(vrtFile); // // // // STEP 3: Warping // // // File warpedFile = warpFile(vrtFile, bbox, crs, width, height, warpOrder, tempFolder, loggingFolder, config.getExecutionTimeout(), config.getGdalWarpingParameters()); if (warpedFile == null || !warpedFile.exists() || !warpedFile.canRead()) { throw new IOException("Unable to get a valid georectified file"); } boolean expand = false; if (cm instanceof IndexColorModel) { expand = true; } else if (cm instanceof ComponentColorModel && cm.getNumComponents() == 1 && cm.getComponentSize()[0] == 1) { expand = true; } if (expand) { removeFiles.add(warpedFile); warpedFile = expandRgba(warpedFile.getAbsolutePath()); } // if we have the output path move the final file there if (Boolean.TRUE.equals(store) && outputPath != null) { File output = new File(outputPath); if (output.exists()) { if (!output.delete()) { throw new WPSException("Output file " + outputPath + " exists but cannot be overwritten"); } } else { File parent = output.getParentFile(); if (!parent.exists()) { if (!parent.mkdirs()) { throw new WPSException("Output file parent directory " + parent.getAbsolutePath() + " does not exist and cannot be created"); } } } if (!warpedFile.renameTo(output)) { throw new WPSException("Could not move " + warpedFile.getAbsolutePath() + " to " + outputPath + ", it's likely a permission issue"); } warpedFile = output; } // mark the output file for deletion at the end of request if (resourceManager != null && !Boolean.TRUE.equals(store)) { resourceManager.addResource(new WPSFileResource(warpedFile)); } // // // // FINAL STEP: Returning the warped gridcoverage // // // reader = new GeoTiffReader(warpedFile); GridCoverage2D cov = addLocationProperty(reader.read(null), warpedFile); Map<String, Object> result = new HashMap<String, Object>(); result.put("result", cov); result.put("path", warpedFile.getAbsolutePath()); return result; } finally { if (reader != null) { try { reader.dispose(); } catch (Throwable t) { // Does nothing } } for (File file : removeFiles) { deleteFile(file); } } }
From source file:org.geotools.gce.imagemosaic.RasterLayerResponse.java
private RenderedImage processGranuleRaster(RenderedImage granule, final int granuleIndex, final int[] alphaIndex, final boolean alphaIn, final PlanarImage[] alphaChannels, final boolean doTransparentColor, final Color transparentColor) { ////from ww w . ja v a2s. c om // INDEX COLOR MODEL EXPANSION // // Take into account the need for an expansions of the original color // model. // // If the original color model is an index color model an expansion // might be requested in case the different palettes are not all the // same. In this case the mosaic operator from JAI would provide wrong // results since it would take the first palette and use that one for // all the other images. // // There is a special case to take into account here. In case the input // images use an IndexColorModel it might happen that the transparent // color is present in some of them while it is not present in some // others. This case is the case where for sure a color expansion is // needed. However we have to take into account that during the masking // phase the images where the requested transparent color was present // will have 4 bands, the other 3. If we want the mosaic to work we // have to add an extra band to the latter type of images for providing // alpha information to them. // // if (rasterManager.expandMe && granule.getColorModel() instanceof IndexColorModel) { granule = new ImageWorker(granule).forceComponentColorModel().getRenderedImage(); } // // TRANSPARENT COLOR MANAGEMENT // if (doTransparentColor) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Support for alpha on input image number " + granuleIndex); granule = ImageUtilities.maskColor(transparentColor, granule); alphaIndex[0] = granule.getColorModel().getNumComponents() - 1; } // // ROI // if (alphaIn || doTransparentColor) { ImageWorker w = new ImageWorker(granule); if (granule.getSampleModel() instanceof MultiPixelPackedSampleModel) w.forceComponentColorModel(); // // ALPHA in INPUT // // I have to select the alpha band and provide it to the final // mosaic operator. I have to force going to ComponentColorModel in // case the image is indexed. // if (granule.getColorModel() instanceof IndexColorModel) { alphaChannels[granuleIndex] = w.forceComponentColorModel().retainLastBand().getPlanarImage(); } else alphaChannels[granuleIndex] = w.retainBands(alphaIndex).getPlanarImage(); } return granule; }
From source file:org.geotools.gce.imagemosaic.RasterLayerResponse.java
/** * This method is responsible for creating a coverage from the supplied {@link RenderedImage}. * /*from www. j ava 2s. c om*/ * @param image * @return * @throws IOException */ private GridCoverage2D prepareCoverage(RenderedImage image) throws IOException { // creating bands final SampleModel sm = image.getSampleModel(); final ColorModel cm = image.getColorModel(); final int numBands = sm.getNumBands(); final GridSampleDimension[] bands = new GridSampleDimension[numBands]; Set<String> bandNames = new HashSet<String>(); // setting bands names. for (int i = 0; i < numBands; i++) { ColorInterpretation colorInterpretation = null; String bandName = null; if (cm != null) { // === color interpretation colorInterpretation = TypeMap.getColorInterpretation(cm, i); if (colorInterpretation == null) { throw new IOException("Unrecognized sample dimension type"); } bandName = colorInterpretation.name(); if (bandNames.contains(bandName)) {// make sure we create no duplicate band names bandName = "Band" + (i + 1); } } else { // no color model bandName = "Band" + (i + 1); colorInterpretation = ColorInterpretation.UNDEFINED; } // sample dimension type final SampleDimensionType st = TypeMap.getSampleDimensionType(sm, i); // set some no data values, as well as Min and Max values final double noData; double min = -Double.MAX_VALUE, max = Double.MAX_VALUE; if (backgroundValues != null) { // sometimes background values are not specified as 1 per each band, therefore we need to be careful noData = backgroundValues[backgroundValues.length > i ? i : 0]; } else { if (st.compareTo(SampleDimensionType.REAL_32BITS) == 0) noData = Float.NaN; else if (st.compareTo(SampleDimensionType.REAL_64BITS) == 0) noData = Double.NaN; else if (st.compareTo(SampleDimensionType.SIGNED_16BITS) == 0) { noData = Short.MIN_VALUE; min = Short.MIN_VALUE; max = Short.MAX_VALUE; } else if (st.compareTo(SampleDimensionType.SIGNED_32BITS) == 0) { noData = Integer.MIN_VALUE; min = Integer.MIN_VALUE; max = Integer.MAX_VALUE; } else if (st.compareTo(SampleDimensionType.SIGNED_8BITS) == 0) { noData = -128; min = -128; max = 127; } else { //unsigned noData = 0; min = 0; // compute max if (st.compareTo(SampleDimensionType.UNSIGNED_1BIT) == 0) max = 1; else if (st.compareTo(SampleDimensionType.UNSIGNED_2BITS) == 0) max = 3; else if (st.compareTo(SampleDimensionType.UNSIGNED_4BITS) == 0) max = 7; else if (st.compareTo(SampleDimensionType.UNSIGNED_8BITS) == 0) max = 255; else if (st.compareTo(SampleDimensionType.UNSIGNED_16BITS) == 0) max = 65535; else if (st.compareTo(SampleDimensionType.UNSIGNED_32BITS) == 0) max = Math.pow(2, 32) - 1; } } bands[i] = new SimplifiedGridSampleDimension(bandName, st, colorInterpretation, noData, min, max, 1, //no scale 0, //no offset null).geophysics(true); } // creating the final coverage by keeping into account the fact that we Map<String, String> properties = null; if (granulesPaths != null) { properties = new HashMap<String, String>(); properties.put(AbstractGridCoverage2DReader.FILE_SOURCE_PROPERTY, granulesPaths); } return coverageFactory.create(rasterManager.getCoverageIdentifier(), image, new GridGeometry2D(new GridEnvelope2D(PlanarImage.wrapRenderedImage(image).getBounds()), PixelInCell.CELL_CORNER, finalGridToWorldCorner, this.mosaicBBox.getCoordinateReferenceSystem(), hints), bands, null, properties); }
From source file:org.geotools.gce.imagemosaic.RasterManager.java
/** * This code tries to load the sample image from which we can extract SM and CM to use when answering to requests * that falls within a hole in the mosaic. * @param configuration //from w w w .j a v a 2 s .c o m */ private void loadSampleImage(MosaicConfigurationBean configuration) { if (this.parentReader.sourceURL == null) { //TODO: I need to define the sampleImage somehow for the ImageMosaicDescriptor case return; } final URL baseURL = this.parentReader.sourceURL; final File baseFile = DataUtilities.urlToFile(baseURL); // in case we do not manage to convert the source URL we leave right awaycd sr if (baseFile == null) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Unable to find sample image for path " + baseURL); return; } String baseName = baseFile.getParent() + "/"; String fileName = null; File sampleImageFile = null; if (configuration != null) { String name = configuration.getName(); if (name != null) { fileName = baseName + name + Utils.SAMPLE_IMAGE_NAME; sampleImageFile = new File(fileName); if (!sampleImageFile.exists() || !sampleImageFile.canRead()) { sampleImageFile = null; } } } if (sampleImageFile == null) { sampleImageFile = new File(baseName + Utils.SAMPLE_IMAGE_NAME); } final RenderedImage sampleImage = Utils.loadSampleImage(sampleImageFile); if (sampleImage != null) { // load SM and CM defaultCM = sampleImage.getColorModel(); defaultSM = sampleImage.getSampleModel(); // default ImageLayout defaultImageLayout = new ImageLayout().setColorModel(defaultCM).setSampleModel(defaultSM); } else if (LOGGER.isLoggable(Level.WARNING)) LOGGER.warning("Unable to find sample image for path " + baseURL); }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.pdf.internal.PdfGraphics2D.java
/** * @noinspection UseOfObsoleteCollectionType * @see Graphics2D#drawRenderedImage(RenderedImage, AffineTransform) *//* w ww . j a v a 2 s . com*/ @Override public void drawRenderedImage(final RenderedImage img, final AffineTransform xform) { final BufferedImage image; if (img instanceof BufferedImage) { image = (BufferedImage) img; } else { 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 properties = new Hashtable(); final String[] keys = img.getPropertyNames(); if (keys != null) { final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { properties.put(keys[i], img.getProperty(keys[i])); } } final BufferedImage result = new BufferedImage(cm, raster, isAlphaPremultiplied, properties); img.copyData(raster); image = result; } drawImage(image, xform, null); }
From source file:org.photovault.image.PhotovaultImage.java
/** Get a histogram of a specific phase of imaging pipeline @param histType What histogram to retrieve. Possible values in PhotovaultImage are//from w w w . j ava 2 s .c om <ul> <li>HISTOGRAM_RGB_CHANNELS - sRGB color space histogam calculated after cropping but before color correction is applied</li> <li>HISTOGRAM_IHS_CHANNELS - IHS color space histogram calculated after RGB color corrections but before saturation correction</li> </ul> Derived classes may add additional histograms @return The histogram from last rendering. TODO: Currently returns <code>null</code> if no rendering has been made. */ public Histogram getHistogram(String histType) { Histogram ret = null; RenderedImage src = null; if (histType.equals(HISTOGRAM_RGB_CHANNELS)) { // Calculate histogram from the image into which color correction was applied src = findNamedRendering(lastRendering, "cropped_image"); } else if (histType.equals(HISTOGRAM_IHS_CHANNELS)) { src = findNamedRendering(lastRendering, "color_corrected_ihs_image"); // src = lastSaturatedRendering.getSources().get(0).getSources().get(0); } if (src != null) { int[] componentSizes = src.getColorModel().getComponentSize(); int numBins[] = new int[componentSizes.length]; double lowValue[] = new double[componentSizes.length]; double highValue[] = new double[componentSizes.length]; for (int n = 0; n < componentSizes.length; n++) { numBins[n] = 1 << componentSizes[n]; lowValue[n] = 0.0; highValue[n] = (double) numBins[n] - 1.0; } RenderedOp histOp = HistogramDescriptor.create(src, null, Integer.valueOf(1), Integer.valueOf(1), numBins, lowValue, highValue, null); ret = (Histogram) histOp.getProperty("histogram"); } return ret; }