Example usage for java.awt.image RenderedImage getSampleModel

List of usage examples for java.awt.image RenderedImage getSampleModel

Introduction

In this page you can find the example usage for java.awt.image RenderedImage getSampleModel.

Prototype

SampleModel getSampleModel();

Source Link

Document

Returns the SampleModel associated with this image.

Usage

From source file:org.geotools.gce.imagemosaic.RasterLayerResponse.java

/**
 * This method is responsible for creating a coverage from the supplied {@link RenderedImage}.
 * /*from  w w w  . ja va 2 s . c  o m*/
 * @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.  ja  v a 2s  .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.mrgeo.rasterops.GeoTiffExporter.java

public static void export(final RenderedImage image, final Bounds bounds, final OutputStream os,
        final boolean replaceNan, final String xmp, final Number nodata) throws IOException {
    OpImageRegistrar.registerMrGeoOps();

    final TIFFEncodeParam param = new TIFFEncodeParam();
    // The version of GDAL that Legion is using requires a tile size > 1
    param.setTileSize(image.getTileWidth(), image.getTileHeight());
    param.setWriteTiled(true);//from w w w.  java2s  .  c o m

    // if the image only has 1 pixel, the value of this pixel changes after compressing (especially
    // if this pixel is no data value. e.g -9999 changes to -8192 when read the image back).
    // So don't do compress if the image has only 1 pixel.
    if (image.getWidth() > 1 && image.getHeight() > 1) {
        // Deflate lossless compression (also known as "Zip-in-TIFF")
        param.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
        param.setDeflateLevel(Deflater.BEST_COMPRESSION);
    }

    final GeoTIFFDirectory dir = new GeoTIFFDirectory();

    // GTModelTypeGeoKey : using geographic coordinate system.
    dir.addGeoKey(new XTIFFField(1024, XTIFFField.TIFF_SHORT, 1, new char[] { 2 }));
    // GTRasterTypeGeoKey : pixel is point
    dir.addGeoKey(new XTIFFField(1025, XTIFFField.TIFF_SHORT, 1, new char[] { 1 }));
    // GeographicTypeGeoKey : 4326 WGS84
    dir.addGeoKey(new XTIFFField(2048, XTIFFField.TIFF_SHORT, 1, new char[] { 4326 }));
    dir.addGeoKey(new XTIFFField(2049, XTIFFField.TIFF_ASCII, 7, new String[] { "WGS 84" }));
    // GeogAngularUnitsGeoKey : Angular Degree
    dir.addGeoKey(new XTIFFField(2054, XTIFFField.TIFF_SHORT, 1, new char[] { 9102 }));
    if (xmp != null) {
        final byte[] b = xmp.getBytes("UTF8");
        dir.addField(new XTIFFField(700, XTIFFField.TIFF_BYTE, b.length, b));
    }
    dir.getFields();

    final double[] tiePoints = new double[6];
    tiePoints[0] = 0.0;
    tiePoints[1] = 0.0;
    tiePoints[2] = 0.0;
    tiePoints[3] = bounds.getMinX();
    tiePoints[4] = bounds.getMaxY();
    tiePoints[5] = 0.0;
    dir.setTiepoints(tiePoints);
    final double[] pixelScale = new double[3];
    pixelScale[0] = bounds.getWidth() / image.getWidth();
    pixelScale[1] = bounds.getHeight() / image.getHeight();
    pixelScale[2] = 0;
    dir.setPixelScale(pixelScale);

    final Vector<TIFFField> fields = toTiffField(dir.getFields());

    RenderedImage output = image;

    final String[] nullValues = new String[1];
    switch (image.getSampleModel().getDataType()) {
    case DataBuffer.TYPE_DOUBLE:
        nullValues[0] = Double.toString(nodata.doubleValue());
        if (replaceNan) {
            output = ReplaceNanDescriptor.create(image, nodata.doubleValue());
        }
        // Tiff exporter doesn't handle doubles. Yuck!
        output = ConvertToFloatDescriptor.create(output);

        // Double.NaN (our default nodata on ingest) should not be written out as nodata on export
        // (i.e. GeoTiffs imported without NODATA metadata field should be exported as such)
        if (!Double.isNaN(nodata.doubleValue())) {
            fields.add(new TIFFField(NULL_TAG, XTIFFField.TIFF_ASCII, 1, nullValues));
        }
        break;
    case DataBuffer.TYPE_FLOAT:
        nullValues[0] = Double.toString(nodata.floatValue());
        if (replaceNan) {
            output = ReplaceNanDescriptor.create(image, nodata.floatValue());
        }
        // Float.NaN (our default nodata on ingest) should not be written out as nodata on export
        // (i.e. GeoTiffs imported without NODATA metadata field should be exported as such)
        if (!Float.isNaN(nodata.floatValue())) {
            fields.add(new TIFFField(NULL_TAG, XTIFFField.TIFF_ASCII, 1, nullValues));
        }
        break;
    case DataBuffer.TYPE_INT:
    case DataBuffer.TYPE_USHORT:
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_BYTE:
        nullValues[0] = Integer.toString(nodata.intValue());
        fields.add(new TIFFField(NULL_TAG, XTIFFField.TIFF_ASCII, 1, nullValues));
        break;
    }

    param.setExtraFields(fields.toArray(new TIFFField[0]));

    EncodeDescriptor.create(output, os, "TIFF", param, null);
}

From source file:org.photovault.imginfo.CreateCopyImageCommand.java

/**
 Helper function to save a rendered image to file
 @param instanceFile The file into which the image will be saved
 @param img Image that willb e saved//from  w  ww .  j  a v a 2  s.  c om
 @param xmpData XPM metadata packet that should be saved with the image
 @throws PhotovaultException if saving does not succeed
 */
protected void saveImage(File instanceFile, RenderedImage img, byte[] xmpData) throws PhotovaultException {
    ImageOutputStream out = null;
    log.debug("Entry: saveImage, file = " + instanceFile.getAbsolutePath());
    try {
        out = new FileImageOutputStream(instanceFile);
    } catch (IOException e) {
        log.error("Error writing image: " + e.getMessage());
        throw new PhotovaultException(e.getMessage());
    }
    if (img.getSampleModel().getSampleSize(0) == 16) {
        log.debug("16 bit image, converting to 8 bits");
        double[] subtract = new double[1];
        subtract[0] = 0;
        double[] divide = new double[1];
        divide[0] = 1. / 256.;
        // Now we can rescale the pixels gray levels:
        ParameterBlock pbRescale = new ParameterBlock();
        pbRescale.add(divide);
        pbRescale.add(subtract);
        pbRescale.addSource(img);
        PlanarImage outputImage = (PlanarImage) JAI.create("rescale", pbRescale, null);
        // Make sure it is a byte image - force conversion.
        ParameterBlock pbConvert = new ParameterBlock();
        pbConvert.addSource(outputImage);
        pbConvert.add(DataBuffer.TYPE_BYTE);
        img = JAI.create("format", pbConvert);
    }

    IIOImage iioimg = new IIOImage(img, null, null);

    /*
     Not all encoders support metadata handling
     */
    Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
    ImageWriter imgwriter = null;
    while (writers.hasNext()) {
        imgwriter = (ImageWriter) writers.next();
        if (imgwriter.getClass().getName().endsWith("JPEGImageEncoder")) {
            // Break on finding the core provider.
            break;
        }
    }
    if (imgwriter == null) {
        System.err.println("Cannot find core JPEG writer!");
    }
    imgwriter.addIIOWriteWarningListener(new IIOWriteWarningListener() {

        public void warningOccurred(ImageWriter arg0, int arg1, String arg2) {
            log.warn("Warning from ImageWriter: " + arg2);
        }
    });
    ImageWriteParam params = imgwriter.getDefaultWriteParam();
    ImageTypeSpecifier its = ImageTypeSpecifier.createFromRenderedImage(img);
    IIOMetadata metadata = imgwriter.getDefaultImageMetadata(its, null);

    IIOMetadataNode metatop = (IIOMetadataNode) metadata.getAsTree("javax_imageio_jpeg_image_1.0");
    NodeList markerSeqNodes = metatop.getElementsByTagName("markerSequence");
    if (markerSeqNodes.getLength() > 0) {
        IIOMetadataNode xmpNode = new IIOMetadataNode("unknown");
        xmpNode.setAttribute("MarkerTag", "225");
        xmpNode.setUserObject(xmpData);
        markerSeqNodes.item(0).appendChild(xmpNode);
    }

    try {
        metadata.setFromTree("javax_imageio_jpeg_image_1.0", metatop);
    } catch (Exception e) {
        log.warn("error editing metadata: " + e.getMessage());
        e.printStackTrace();
        throw new PhotovaultException("error setting image metadata: \n" + e.getMessage());
    }

    iioimg.setMetadata(metadata);

    try {
        imgwriter.setOutput(out);
        imgwriter.write(iioimg);
    } catch (IOException e) {
        log.warn("Exception while encoding" + e.getMessage());
        throw new PhotovaultException(
                "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            log.warn("Exception while closing file: " + e.getMessage());
            imgwriter.dispose();
            throw new PhotovaultException(
                    "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());

        }
        imgwriter.dispose();
    }
    log.debug("Exit: saveImage");
}

From source file:org.photovault.imginfo.PhotoInfo.java

/**
 Helper function to save a rendered image to file
 @param instanceFile The file into which the image will be saved
 @param img Image that willb e saved/*from   w w  w . j a v a 2s  .  c  o m*/
 @throws PhotovaultException if saving does not succeed
 */
protected void saveInstance(File instanceFile, RenderedImage img) throws PhotovaultException {
    OutputStream out = null;
    log.debug("Entry: saveInstance, file = " + instanceFile.getAbsolutePath());
    try {
        out = new FileOutputStream(instanceFile.getAbsolutePath());
    } catch (IOException e) {
        log.error("Error writing thumbnail: " + e.getMessage());
        throw new PhotovaultException(e.getMessage());
    }
    if (img.getSampleModel().getSampleSize(0) == 16) {
        log.debug("16 bit image, converting to 8 bits");
        double[] subtract = new double[1];
        subtract[0] = 0;
        double[] divide = new double[1];
        divide[0] = 1. / 256.;
        // Now we can rescale the pixels gray levels:
        ParameterBlock pbRescale = new ParameterBlock();
        pbRescale.add(divide);
        pbRescale.add(subtract);
        pbRescale.addSource(img);
        PlanarImage outputImage = (PlanarImage) JAI.create("rescale", pbRescale, null);
        // Make sure it is a byte image - force conversion.
        ParameterBlock pbConvert = new ParameterBlock();
        pbConvert.addSource(outputImage);
        pbConvert.add(DataBuffer.TYPE_BYTE);
        img = JAI.create("format", pbConvert);
    }
    JPEGEncodeParam encodeParam = new JPEGEncodeParam();
    ImageEncoder encoder = ImageCodec.createImageEncoder("JPEG", out, encodeParam);
    try {
        log.debug("starting JPEG enconde");
        encoder.encode(img);
        log.debug("done JPEG encode");
        out.close();
        // origImage.dispose();
    } catch (Exception e) {
        log.warn("Exception while encoding" + e.getMessage());
        throw new PhotovaultException(
                "Error writing instance " + instanceFile.getAbsolutePath() + ": " + e.getMessage());
    }
    log.debug("Exit: saveInstance");
}