Example usage for java.awt.image DataBuffer TYPE_FLOAT

List of usage examples for java.awt.image DataBuffer TYPE_FLOAT

Introduction

In this page you can find the example usage for java.awt.image DataBuffer TYPE_FLOAT.

Prototype

int TYPE_FLOAT

To view the source code for java.awt.image DataBuffer TYPE_FLOAT.

Click Source Link

Document

Tag for float data.

Usage

From source file:eu.udig.catalog.jgrass.utils.JGrassCatalogUtilities.java

/**
 * Creates a {@link WritableRaster writable raster}.
 * /*from  ww  w. j  ava 2  s . c  o m*/
 * @param width width of the raster to create.
 * @param height height of the raster to create.
 * @param dataClass data type for the raster. If <code>null</code>, defaults to double.
 * @param sampleModel the samplemodel to use. If <code>null</code>, defaults to 
 *                  <code>new ComponentSampleModel(dataType, width, height, 1, width, new int[]{0});</code>.
 * @param value value to which to set the raster to. If null, the default of the raster creation is 
 *                  used, which is 0.
 * @return a {@link WritableRaster writable raster}.
 */
public static WritableRaster createDoubleWritableRaster(int width, int height, Class<?> dataClass,
        SampleModel sampleModel, Double value) {
    int dataType = DataBuffer.TYPE_DOUBLE;
    if (dataClass != null) {
        if (dataClass.isAssignableFrom(Integer.class)) {
            dataType = DataBuffer.TYPE_INT;
        } else if (dataClass.isAssignableFrom(Float.class)) {
            dataType = DataBuffer.TYPE_FLOAT;
        } else if (dataClass.isAssignableFrom(Byte.class)) {
            dataType = DataBuffer.TYPE_BYTE;
        }
    }
    if (sampleModel == null) {
        sampleModel = new ComponentSampleModel(dataType, width, height, 1, width, new int[] { 0 });
    }

    WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, null);
    if (value != null) {
        // autobox only once
        double v = value;

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                raster.setSample(x, y, 0, v);
            }
        }
    }
    return raster;
}

From source file:it.geosolutions.jaiext.range.RangeTest.java

private void checkRangeConversion(Range range) {
    checkRangeConversion(range, DataBuffer.TYPE_BYTE);
    checkRangeConversion(range, DataBuffer.TYPE_DOUBLE);
    checkRangeConversion(range, DataBuffer.TYPE_FLOAT);
    checkRangeConversion(range, DataBuffer.TYPE_INT);
    checkRangeConversion(range, DataBuffer.TYPE_SHORT);
    checkRangeConversion(range, DataBuffer.TYPE_USHORT);
}

From source file:it.geosolutions.geobatch.destination.vulnerability.VulnerabilityComputation.java

/**
 * Method used for merging the input Rasters into a 2 images, one for human targets and the other for not human targets
 * /*  w  w  w.j  a  v  a 2s  .com*/
 * @param humanTargets
 * @param notHumanTargets
 * @param bandPerTargetH
 * @param bandPerTargetNH
 * @throws IOException
 * @throws java.awt.geom.NoninvertibleTransformException
 * @throws TransformException
 * @throws MismatchedDimensionException
 */
public RenderedImage[] rasterCalculation(Map<Integer, TargetInfo> bandPerTargetH,
        Map<Integer, TargetInfo> bandPerTargetNH) throws IOException,
        java.awt.geom.NoninvertibleTransformException, MismatchedDimensionException, TransformException {
    // Initialization of the images
    RenderedImage humanTargets = null;
    RenderedImage notHumanTargets = null;
    String basePath = System.getProperty(RASTER_PATH_PROP, "");
    if (!basePath.equals("")) {
        basePath = basePath + File.separator + codicePartner;
    }
    // Read of the resources
    Map vulnerabilityConf = (Map) readResourceFromXML("/vulnerability.xml");
    // Vulnerability engine used for extracting the Targets
    VulnerabilityStatsEngine vsengine = new VulnerabilityStatsEngine(basePath, vulnerabilityConf, dataStore,
            DISTANCE_TYPE_NAME, pixelArea);
    // Target Map
    Map<String, TargetInfo> targetInfo = vsengine.getTargetInfo();

    /*
     * Creation of 2 images: one for the HUMAN TARGETS and the other for NOT HUMAN TARGETS
     */
    // List of Human Targets
    List<RenderedImage> humanList = new ArrayList<RenderedImage>();

    // List of Not Human Targets
    List<RenderedImage> notHumanList = new ArrayList<RenderedImage>();

    // Counters indicating which band is associated to the TargetInfo and
    // Image
    int humanBandCounter = 0;
    int notHumanBandCounter = 0;

    // Iterator on all the targets
    Iterator<String> rasterIter = targetInfo.keySet().iterator();

    // Initializations of the parameters for merging the input rasters
    Envelope2D globalBBOXHuman = null;
    Envelope2D globalBBOXNotHuman = null;
    List<AffineTransform> tfHuman = new ArrayList<AffineTransform>();
    List<AffineTransform> tfNotHuman = new ArrayList<AffineTransform>();
    AffineTransform g2WHuman = null;
    AffineTransform g2WNotHuman = null;
    // Cycle on all the rasters
    while (rasterIter.hasNext()) {
        // save the ID of this target
        String targetID = rasterIter.next();

        // Load the target manager, init its status and check if the actual
        // distance is a valid distance for it
        TargetInfo info = targetInfo.get(targetID);

        // Getting of the transformation parameters
        GridGeometry2D gg2D = info.getGG2D();
        Envelope2D envelope = gg2D.getEnvelope2D();
        AffineTransform w2g = (AffineTransform) gg2D.getCRSToGrid2D(PixelOrientation.UPPER_LEFT);
        // getting information about current Target
        TargetManager manager = info.getManager();

        // Image associated to the current target
        RenderedImage newImage = info.getRaster();
        // Image data type
        int imgDataType = newImage.getSampleModel().getDataType();
        // Check if the image really exists
        if (newImage != null) {
            // If the target is human
            if (manager.isHumanTarget()) {
                // Other check for ensuring the target is correct
                if (imgDataType != DataBuffer.TYPE_FLOAT) {
                    System.out.println("Wrong data type");
                }

                // perform union
                if (globalBBOXHuman == null) {
                    globalBBOXHuman = new Envelope2D(envelope);
                } else {
                    globalBBOXHuman.include(envelope);
                }
                // Selection of the first g2w transform as the global one
                if (g2WHuman == null) {
                    g2WHuman = (AffineTransform) gg2D.getGridToCRS2D(PixelOrientation.UPPER_LEFT);
                }

                // Creation of the transformation from destination Raster space to source Raster space
                AffineTransform temp = new AffineTransform(w2g);
                temp.concatenate(g2WHuman);
                tfHuman.add(temp);

                // Addition of the TargetInfo of this target
                bandPerTargetH.put(humanBandCounter, info);
                // Update of the bandCounter
                humanBandCounter++;
                // Addition of the image to the associated list
                humanList.add(newImage);

            } else {
                // Other check for ensuring the target is correct
                if (imgDataType != DataBuffer.TYPE_BYTE) {
                    System.out.println("Wrong data type");
                }

                // perform union
                if (globalBBOXNotHuman == null) {
                    globalBBOXNotHuman = envelope;
                } else {
                    globalBBOXNotHuman.include(envelope);
                }
                // Selection of the first g2w transform as the global one
                if (g2WNotHuman == null) {
                    g2WNotHuman = (AffineTransform) gg2D.getGridToCRS2D(PixelOrientation.UPPER_LEFT);
                }
                // Creation of the transformation from destination Raster space to source Raster space
                AffineTransform temp = new AffineTransform(w2g);
                temp.concatenate(g2WNotHuman);
                tfNotHuman.add(temp);

                // Addition of the TargetInfo of this target
                bandPerTargetNH.put(notHumanBandCounter, info);
                // Update of the bandCounter
                notHumanBandCounter++;
                // Addition of the image to the associated list
                notHumanList.add(newImage);
            }
        }
    }

    // computing final raster space for the two targets
    GridGeometry2D humanGG2D = new GridGeometry2D(PixelInCell.CELL_CORNER, new AffineTransform2D(g2WHuman),
            globalBBOXHuman, null);
    globalBBOXHuman = humanGG2D.getEnvelope2D(); // take into account integer pixel roundings

    GridGeometry2D noHumanGG2D = new GridGeometry2D(PixelInCell.CELL_CORNER, new AffineTransform2D(g2WNotHuman),
            globalBBOXNotHuman, null);
    globalBBOXNotHuman = noHumanGG2D.getEnvelope2D(); // take into account integer pixel roundings

    // BandMerge of the images
    RenderedImage[] imagesHuman = new RenderedImage[humanList.size()];
    RenderedImage[] imagesNotHuman = new RenderedImage[notHumanList.size()];
    // Setting of the final layout
    ImageLayout layoutH = new ImageLayout2();
    GridEnvelope2D gridRange2D = humanGG2D.getGridRange2D();
    layoutH.setMinX(gridRange2D.x);
    layoutH.setMinY(gridRange2D.y);
    layoutH.setWidth(gridRange2D.width);
    layoutH.setHeight(gridRange2D.height);
    // Definition of the TileCache
    RenderingHints hintsH = new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache());
    // Setting of the layout as hint
    hintsH.put(JAI.KEY_IMAGE_LAYOUT, layoutH);
    // Merging of the input human targets
    humanTargets = BandMergeDescriptor.create(null, 0, hintsH, tfHuman, humanList.toArray(imagesHuman));
    // Setting of the final layout
    ImageLayout layoutNH = new ImageLayout2();
    gridRange2D = noHumanGG2D.getGridRange2D();
    layoutNH.setMinX(gridRange2D.x);
    layoutNH.setMinY(gridRange2D.y);
    layoutNH.setWidth(gridRange2D.width);
    layoutNH.setHeight(gridRange2D.height);
    // Definition of the TileCache
    RenderingHints hintsNH = new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache());
    hintsNH.put(JAI.KEY_IMAGE_LAYOUT, layoutNH);
    // Merging of the input not human targets
    notHumanTargets = BandMergeDescriptor.create(null, 0, hintsNH, tfNotHuman,
            notHumanList.toArray(imagesNotHuman));

    // cache the final images
    humanTargets = NullDescriptor.create(humanTargets,
            new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache()));

    notHumanTargets = NullDescriptor.create(notHumanTargets,
            new RenderingHints(JAI.KEY_TILE_CACHE, JAI.getDefaultInstance().getTileCache()));

    // Clearing of the initial lists
    notHumanList.clear();
    humanList.clear();
    // create a new array of the new images
    return new RenderedImage[] { humanTargets, notHumanTargets };
}

From source file:nitf.imageio.NITFReader.java

@Override
public Raster readRaster(int imageIndex, ImageReadParam param) throws IOException {
    checkIndex(imageIndex);/* w w  w  .  ja v a 2 s.c  om*/

    Rectangle sourceRegion = new Rectangle();
    Rectangle destRegion = new Rectangle();
    computeRegions(param, getWidth(imageIndex), getHeight(imageIndex), null, sourceRegion, destRegion);

    // Set everything to default values
    int sourceXSubsampling = param != null ? param.getSourceXSubsampling() : 1;
    int sourceYSubsampling = param != null ? param.getSourceYSubsampling() : 1;
    Point destinationOffset = param != null ? param.getDestinationOffset() : new Point(0, 0);

    ImageSubheader subheader;
    try {
        subheader = record.getImages()[imageIndex].getSubheader();
    } catch (NITFException e) {
        throw new IOException(ExceptionUtils.getStackTrace(e));
    }
    String irep = subheader.getImageRepresentation().getStringData().trim();
    String pvType = subheader.getPixelValueType().getStringData().trim();
    int nbpp = subheader.getNumBitsPerPixel().getIntData();
    int bandCount = subheader.getBandCount();

    // make the band offsets array, for the output
    int[] bandOffsets = null;
    int[] sourceBands = param != null ? param.getSourceBands() : null;
    if (param != null && param.getDestinationBands() != null)
        bandOffsets = param.getDestinationBands();
    else if (param != null && sourceBands != null) {
        bandOffsets = new int[sourceBands.length];
        for (int i = 0; i < bandOffsets.length; i++)
            bandOffsets[i] = sourceBands[i];
    } else {
        // Setup band offsets -- TODO should we really read ALL bands by
        // default?
        bandOffsets = new int[bandCount];
        for (int i = 0; i < bandOffsets.length; i++)
            bandOffsets[i] = i;
    }

    int nBytes = ((nbpp - 1) / 8) + 1;

    int bufType = -1;

    // byte
    if (nBytes == 1) {
        bufType = DataBuffer.TYPE_BYTE;
    }
    // short
    else if (nBytes == 2) {
        bufType = DataBuffer.TYPE_USHORT;
    }
    // float
    else if (nBytes == 4 && pvType.equals("R")) {
        bufType = DataBuffer.TYPE_FLOAT;
    }
    // double
    else if (nBytes == 8 && pvType.equals("R")) {
        bufType = DataBuffer.TYPE_DOUBLE;
    } else {
        throw new NotImplementedException("not yet implemented");
    }

    WritableRaster ras = ImageIOUtils.makeGenericPixelInterleavedWritableRaster(destRegion.width,
            destRegion.height, bandOffsets.length, bufType);
    checkReadParamBandSettings(param, bandCount, ras.getSampleModel().getNumBands());
    readRaster(imageIndex, sourceRegion, destRegion, sourceXSubsampling, sourceYSubsampling, bandOffsets,
            nBytes, destinationOffset, ras);
    return ras;
}

From source file:org.apache.xmlgraphics.ps.PSImageUtils.java

/**
 * Extracts a packed RGB integer array of a RenderedImage.
 * @param img the image//w  w w . j a  v  a  2s. c o m
 * @param startX the starting X coordinate
 * @param startY the starting Y coordinate
 * @param w the width of the cropped image
 * @param h the height of the cropped image
 * @param rgbArray the prepared integer array to write to
 * @param offset offset in the target array
 * @param scansize width of a row in the target array
 * @return the populated integer array previously passed in as rgbArray parameter
 */
public static int[] getRGB(RenderedImage img, int startX, int startY, int w, int h, int[] rgbArray, int offset,
        int scansize) {
    Raster raster = img.getData();
    int yoff = offset;
    int off;
    Object data;
    int nbands = raster.getNumBands();
    int dataType = raster.getDataBuffer().getDataType();
    switch (dataType) {
    case DataBuffer.TYPE_BYTE:
        data = new byte[nbands];
        break;
    case DataBuffer.TYPE_USHORT:
        data = new short[nbands];
        break;
    case DataBuffer.TYPE_INT:
        data = new int[nbands];
        break;
    case DataBuffer.TYPE_FLOAT:
        data = new float[nbands];
        break;
    case DataBuffer.TYPE_DOUBLE:
        data = new double[nbands];
        break;
    default:
        throw new IllegalArgumentException("Unknown data buffer type: " + dataType);
    }

    if (rgbArray == null) {
        rgbArray = new int[offset + h * scansize];
    }

    ColorModel colorModel = img.getColorModel();
    for (int y = startY; y < startY + h; y++, yoff += scansize) {
        off = yoff;
        for (int x = startX; x < startX + w; x++) {
            rgbArray[off++] = colorModel.getRGB(raster.getDataElements(x, y, data));
        }
    }

    return rgbArray;
}

From source file:org.geoserver.jai.ConcurrentTileFactory.java

/**
 * Builds a new tile, eventually recycling the data array backing it
 *///  w w  w .  j ava 2  s .c  om
public WritableRaster createTile(SampleModel sampleModel, Point location) {
    // sanity checks
    if (sampleModel == null) {
        throw new NullPointerException("sampleModel cannot be null");
    }
    if (location == null) {
        location = new Point(0, 0);
    }

    DataBuffer db = null;

    // get the three elements making the key into the recycled array map
    int type = sampleModel.getTransferType();
    long numBanks = 0;
    long size = 0;
    if (sampleModel instanceof ComponentSampleModel) {
        ComponentSampleModel csm = (ComponentSampleModel) sampleModel;
        numBanks = getNumBanksCSM(csm);
        size = getBufferSizeCSM(csm);
    } else if (sampleModel instanceof MultiPixelPackedSampleModel) {
        MultiPixelPackedSampleModel mppsm = (MultiPixelPackedSampleModel) sampleModel;
        numBanks = 1;
        int dataTypeSize = DataBuffer.getDataTypeSize(type);
        size = mppsm.getScanlineStride() * mppsm.getHeight()
                + (mppsm.getDataBitOffset() + dataTypeSize - 1) / dataTypeSize;
    } else if (sampleModel instanceof SinglePixelPackedSampleModel) {
        SinglePixelPackedSampleModel sppsm = (SinglePixelPackedSampleModel) sampleModel;
        numBanks = 1;
        size = sppsm.getScanlineStride() * (sppsm.getHeight() - 1) + sppsm.getWidth();
    }

    if (size > 0) {
        // try to build a new data buffer starting from 
        Object array = recycledArrays.getRecycledArray(type, numBanks, size);
        if (array != null) {
            switch (type) {
            case DataBuffer.TYPE_BYTE: {
                byte[][] bankData = (byte[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (byte) 0);
                }
                db = new DataBufferByte(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_USHORT: {
                short[][] bankData = (short[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (short) 0);
                }
                db = new DataBufferUShort(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_SHORT: {
                short[][] bankData = (short[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], (short) 0);
                }
                db = new DataBufferShort(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_INT: {
                int[][] bankData = (int[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0);
                }
                db = new DataBufferInt(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_FLOAT: {
                float[][] bankData = (float[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0.0F);
                }
                db = DataBufferUtils.createDataBufferFloat(bankData, (int) size);
            }
                break;
            case DataBuffer.TYPE_DOUBLE: {
                double[][] bankData = (double[][]) array;
                for (int i = 0; i < numBanks; i++) {
                    Arrays.fill(bankData[i], 0.0);
                }
                db = DataBufferUtils.createDataBufferDouble(bankData, (int) size);
            }
                break;
            default:
                throw new IllegalArgumentException("Unknown array type");
            }
        }
    }

    if (db == null) {
        db = sampleModel.createDataBuffer();
    }

    return Raster.createWritableRaster(sampleModel, db, location);
}

From source file:org.geotools.imageio.netcdf.NetCDFImageReader.java

/**
 * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam)
 *///ww w .j a v  a  2s .  c  om
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    clearAbortRequest();

    final Slice2DIndex slice2DIndex = getSlice2DIndex(imageIndex);
    final String variableName = slice2DIndex.getVariableName();
    final VariableAdapter wrapper = getCoverageDescriptor(new NameImpl(variableName));

    /*
     * Fetches the parameters that are not already processed by utility
     * methods like 'getDestination' or 'computeRegions' (invoked below).
     */
    final int strideX, strideY;
    // final int[] srcBands;
    final int[] dstBands;
    if (param != null) {
        strideX = param.getSourceXSubsampling();
        strideY = param.getSourceYSubsampling();
        // srcBands = param.getSourceBands();
        dstBands = param.getDestinationBands();
    } else {
        strideX = 1;
        strideY = 1;
        // srcBands = null;
        dstBands = null;
    }

    /*
     * Gets the destination image of appropriate size. We create it now
     * since it is a convenient way to get the number of destination bands.
     */
    final int width = wrapper.getWidth();
    final int height = wrapper.getHeight();
    /*
     * Computes the source region (in the NetCDF file) and the destination
     * region (in the buffered image). Copies those informations into UCAR
     * Range structure.
     */
    final Rectangle srcRegion = new Rectangle();
    final Rectangle destRegion = new Rectangle();
    computeRegions(param, width, height, null, srcRegion, destRegion);

    // Flipping is needed only when the input latitude coordinate is ordered
    // from min to max
    if (needsFlipping) {
        flipVertically(param, height, srcRegion);
    }
    int destWidth = destRegion.x + destRegion.width;
    int destHeight = destRegion.y + destRegion.height;

    /*
     * build the ranges that need to be read from each 
     * dimension based on the source region
     */
    final List<Range> ranges = new LinkedList<Range>();
    try {
        // add the ranges the COARDS way: T, Z, Y, X
        // T
        int first = slice2DIndex.getTIndex();
        int length = 1;
        int stride = 1;
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Z
        first = slice2DIndex.getZIndex();
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Y
        first = srcRegion.y;
        length = srcRegion.height;
        stride = strideY;
        ranges.add(new Range(first, first + length - 1, stride));
        // X
        first = srcRegion.x;
        length = srcRegion.width;
        stride = strideX;
        ranges.add(new Range(first, first + length - 1, stride));
    } catch (InvalidRangeException e) {
        throw netcdfFailure(e);
    }

    /*
     * create the section of multidimensional array indices
     * that defines the exact data that need to be read 
     * for this image index and parameters 
     */
    final Section section = new Section(ranges);

    /*
     * Setting SampleModel and ColorModel.
     */
    final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight);
    final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel);

    final WritableRaster raster = Raster.createWritableRaster(sampleModel, new Point(0, 0));
    final BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

    CoordinateAxis axis = wrapper.variableDS.getCoordinateSystems().get(0).getLatAxis();
    boolean flipYAxis = false;
    try {
        Array yAxisStart = axis.read(new Section().appendRange(2));
        float y1 = yAxisStart.getFloat(0);
        float y2 = yAxisStart.getFloat(1);
        if (y2 > y1) {
            flipYAxis = true;
        }
    } catch (InvalidRangeException e) {
        throw new RuntimeException(e);
    }
    /*
     * Reads the requested sub-region only.
     */
    processImageStarted(imageIndex);
    final int numDstBands = 1;
    final float toPercent = 100f / numDstBands;
    final int type = raster.getSampleModel().getDataType();
    final int xmin = destRegion.x;
    final int ymin = destRegion.y;
    final int xmax = destRegion.width + xmin;
    final int ymax = destRegion.height + ymin;
    for (int zi = 0; zi < numDstBands; zi++) {
        // final int srcBand = (srcBands == null) ? zi : srcBands[zi];
        final int dstBand = (dstBands == null) ? zi : dstBands[zi];
        final Array array;
        try {
            // TODO leak through
            array = wrapper.variableDS.read(section);
        } catch (InvalidRangeException e) {
            throw netcdfFailure(e);
        }
        if (flipYAxis) {
            final IndexIterator it = array.getIndexIterator();
            for (int y = ymax; --y >= ymin;) {
                for (int x = xmin; x < xmax; x++) {
                    switch (type) {
                    case DataBuffer.TYPE_DOUBLE: {
                        raster.setSample(x, y, dstBand, it.getDoubleNext());
                        break;
                    }
                    case DataBuffer.TYPE_FLOAT: {
                        raster.setSample(x, y, dstBand, it.getFloatNext());
                        break;
                    }
                    case DataBuffer.TYPE_BYTE: {
                        byte b = it.getByteNext();
                        // int myByte = (0x000000FF & ((int) b));
                        // short anUnsignedByte = (short) myByte;
                        // raster.setSample(x, y, dstBand, anUnsignedByte);
                        raster.setSample(x, y, dstBand, b);
                        break;
                    }
                    default: {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                        break;
                    }
                    }
                }
            }
        } else {
            switch (type) {
            case DataBuffer.TYPE_DOUBLE: {
                DoubleBuffer doubleBuffer = array.getDataAsByteBuffer().asDoubleBuffer();
                double[] samples = new double[destRegion.width * destRegion.height];
                doubleBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            }
            case DataBuffer.TYPE_FLOAT:
                float[] samples = new float[destRegion.width * destRegion.height];
                FloatBuffer floatBuffer = array.getDataAsByteBuffer().asFloatBuffer();
                floatBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            case DataBuffer.TYPE_BYTE:
                //THIS ONLY WORKS FOR ONE BAND!!
                raster.setDataElements(xmin, ymin, destRegion.width, destRegion.height,
                        array.getDataAsByteBuffer().array());
                break;
            case DataBuffer.TYPE_INT:
                IntBuffer intBuffer = array.getDataAsByteBuffer().asIntBuffer();
                int[] intSamples = new int[destRegion.width * destRegion.height];
                intBuffer.get(intSamples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, intSamples);
                break;
            default: {
                final IndexIterator it = array.getIndexIterator();
                for (int y = ymin; y < ymax; y++) {
                    for (int x = xmin; x < xmax; x++) {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                    }
                }
                break;
            }

            }

        }
        /*
         * Checks for abort requests after reading. It would be a waste of a
         * potentially good image (maybe the abort request occurred after we
         * just finished the reading) if we didn't implemented the
         * 'isCancel()' method. But because of the later, which is checked
         * by the NetCDF library, we can't assume that the image is
         * complete.
         */
        if (abortRequested()) {
            processReadAborted();
            return image;
        }
        /*
         * Reports progress here, not in the deeper loop, because the costly
         * part is the call to 'variable.read(...)' which can't report
         * progress. The loop that copy pixel values is fast, so reporting
         * progress there would be pointless.
         */
        processImageProgress(zi * toPercent);
    }
    processImageComplete();
    return image;
}

From source file:org.geotools.imageio.unidata.UnidataImageReader.java

/**
 * @see javax.imageio.ImageReader#read(int, javax.imageio.ImageReadParam)
 *//*from  ww w  .  ja  va  2 s .c  om*/
@Override
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
    clearAbortRequest();

    final UnidataSlice2DIndex slice2DIndex = getSlice2DIndex(imageIndex);
    final String variableName = slice2DIndex.getVariableName();
    final UnidataVariableAdapter wrapper = getCoverageDescriptor(new NameImpl(variableName));

    /*
     * Fetches the parameters that are not already processed by utility
     * methods like 'getDestination' or 'computeRegions' (invoked below).
     */
    final int strideX, strideY;
    // final int[] srcBands;
    final int[] dstBands;
    if (param != null) {
        strideX = param.getSourceXSubsampling();
        strideY = param.getSourceYSubsampling();
        // srcBands = param.getSourceBands();
        dstBands = param.getDestinationBands();
    } else {
        strideX = 1;
        strideY = 1;
        // srcBands = null;
        dstBands = null;
    }

    /*
     * Gets the destination image of appropriate size. We create it now
     * since it is a convenient way to get the number of destination bands.
     */
    final int width = wrapper.getWidth();
    final int height = wrapper.getHeight();
    /*
     * Computes the source region (in the NetCDF file) and the destination
     * region (in the buffered image). Copies those informations into UCAR
     * Range structure.
     */
    final Rectangle srcRegion = new Rectangle();
    final Rectangle destRegion = new Rectangle();
    computeRegions(param, width, height, null, srcRegion, destRegion);
    flipVertically(param, height, srcRegion);
    int destWidth = destRegion.x + destRegion.width;
    int destHeight = destRegion.y + destRegion.height;

    /*
     * build the ranges that need to be read from each 
     * dimension based on the source region
     */
    final List<Range> ranges = new LinkedList<Range>();
    try {
        // add the ranges the COARDS way: T, Z, Y, X
        // T
        int first = slice2DIndex.getTIndex();
        int length = 1;
        int stride = 1;
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Z
        first = slice2DIndex.getZIndex();
        if (first != -1) {
            ranges.add(new Range(first, first + length - 1, stride));
        }
        // Y
        first = srcRegion.y;
        length = srcRegion.height;
        stride = strideY;
        ranges.add(new Range(first, first + length - 1, stride));
        // X
        first = srcRegion.x;
        length = srcRegion.width;
        stride = strideX;
        ranges.add(new Range(first, first + length - 1, stride));
    } catch (InvalidRangeException e) {
        throw netcdfFailure(e);
    }

    /*
     * create the section of multidimensional array indices
     * that defines the exact data that need to be read 
     * for this image index and parameters 
     */
    final Section section = new Section(ranges);

    /*
     * Setting SampleModel and ColorModel.
     */
    final SampleModel sampleModel = wrapper.getSampleModel().createCompatibleSampleModel(destWidth, destHeight);
    final ColorModel colorModel = ImageIOUtilities.createColorModel(sampleModel);

    final WritableRaster raster = Raster.createWritableRaster(sampleModel, new Point(0, 0));
    final BufferedImage image = new BufferedImage(colorModel, raster, colorModel.isAlphaPremultiplied(), null);

    CoordinateAxis axis = wrapper.variableDS.getCoordinateSystems().get(0).getLatAxis();
    boolean flipYAxis = false;
    try {
        Array yAxisStart = axis.read(new Section().appendRange(2));
        float y1 = yAxisStart.getFloat(0);
        float y2 = yAxisStart.getFloat(1);
        if (y2 > y1) {
            flipYAxis = true;
        }
    } catch (InvalidRangeException e) {
        throw new RuntimeException(e);
    }
    /*
     * Reads the requested sub-region only.
     */
    processImageStarted(imageIndex);
    final int numDstBands = 1;
    final float toPercent = 100f / numDstBands;
    final int type = raster.getSampleModel().getDataType();
    final int xmin = destRegion.x;
    final int ymin = destRegion.y;
    final int xmax = destRegion.width + xmin;
    final int ymax = destRegion.height + ymin;
    for (int zi = 0; zi < numDstBands; zi++) {
        // final int srcBand = (srcBands == null) ? zi : srcBands[zi];
        final int dstBand = (dstBands == null) ? zi : dstBands[zi];
        final Array array;
        try {
            // TODO leak through
            array = wrapper.variableDS.read(section);
        } catch (InvalidRangeException e) {
            throw netcdfFailure(e);
        }
        if (flipYAxis) {
            final IndexIterator it = array.getIndexIterator();
            for (int y = ymax; --y >= ymin;) {
                for (int x = xmin; x < xmax; x++) {
                    switch (type) {
                    case DataBuffer.TYPE_DOUBLE: {
                        raster.setSample(x, y, dstBand, it.getDoubleNext());
                        break;
                    }
                    case DataBuffer.TYPE_FLOAT: {
                        raster.setSample(x, y, dstBand, it.getFloatNext());
                        break;
                    }
                    case DataBuffer.TYPE_BYTE: {
                        byte b = it.getByteNext();
                        // int myByte = (0x000000FF & ((int) b));
                        // short anUnsignedByte = (short) myByte;
                        // raster.setSample(x, y, dstBand, anUnsignedByte);
                        raster.setSample(x, y, dstBand, b);
                        break;
                    }
                    default: {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                        break;
                    }
                    }
                }
            }
        } else {
            switch (type) {
            case DataBuffer.TYPE_DOUBLE: {
                DoubleBuffer doubleBuffer = array.getDataAsByteBuffer().asDoubleBuffer();
                double[] samples = new double[destRegion.width * destRegion.height];
                doubleBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            }
            case DataBuffer.TYPE_FLOAT:
                float[] samples = new float[destRegion.width * destRegion.height];
                FloatBuffer floatBuffer = array.getDataAsByteBuffer().asFloatBuffer();
                floatBuffer.get(samples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, samples);
                break;
            case DataBuffer.TYPE_BYTE:
                //THIS ONLY WORKS FOR ONE BAND!!
                raster.setDataElements(xmin, ymin, destRegion.width, destRegion.height,
                        array.getDataAsByteBuffer().array());
                break;
            case DataBuffer.TYPE_INT:
                IntBuffer intBuffer = array.getDataAsByteBuffer().asIntBuffer();
                int[] intSamples = new int[destRegion.width * destRegion.height];
                intBuffer.get(intSamples);
                raster.setSamples(xmin, ymin, destRegion.width, destRegion.height, dstBand, intSamples);
                break;
            default: {
                final IndexIterator it = array.getIndexIterator();
                for (int y = ymin; y < ymax; y++) {
                    for (int x = xmin; x < xmax; x++) {
                        raster.setSample(x, y, dstBand, it.getIntNext());
                    }
                }
                break;
            }

            }

        }
        /*
         * Checks for abort requests after reading. It would be a waste of a
         * potentially good image (maybe the abort request occurred after we
         * just finished the reading) if we didn't implemented the
         * 'isCancel()' method. But because of the later, which is checked
         * by the NetCDF library, we can't assume that the image is
         * complete.
         */
        if (abortRequested()) {
            processReadAborted();
            return image;
        }
        /*
         * Reports progress here, not in the deeper loop, because the costly
         * part is the call to 'variable.read(...)' which can't report
         * progress. The loop that copy pixel values is fast, so reporting
         * progress there would be pointless.
         */
        processImageProgress(zi * toPercent);
    }
    processImageComplete();
    return image;
}

From source file:org.kalypso.grid.GeoGridUtilities.java

/**
 * This function creates a TIFF using the given file as target and sets the value from the grid to it.
 * //from  w ww. j ava 2s .co  m
 * @param grid
 *          The values of the TIFF will be read from this grid.
 * @param file
 *          The binary grid will be serialized to this file.
 * @param monitor
 *          A progress monitor.
 */
public static void toTiff(final IGeoGrid grid, final File file, IProgressMonitor monitor)
        throws GeoGridException {
    /* Monitor. */
    if (monitor == null)
        monitor = new NullProgressMonitor();

    try {
        /* Monitor. */
        monitor.beginTask("Creating TIFF...", 1000);
        monitor.subTask("Creating TIFF...");

        /* Create the TIFF. */
        final TiledImage image = TIFFUtilities.createTiff(DataBuffer.TYPE_FLOAT, grid.getSizeX(),
                grid.getSizeY());

        /* Monitor. */
        monitor.worked(250);
        monitor.subTask("Copying values...");

        /* Copy the values. */
        TIFFUtilities.copyGeoGridToTiff(grid, image);

        /* Monitor. */
        monitor.worked(500);
        monitor.subTask("Saving TIFF...");

        /* Save the TIFF. */
        TIFFUtilities.saveTiff(image, 100, 100, file);

        /* Monitor. */
        monitor.worked(250);
    } finally {
        /* Monitor. */
        monitor.done();
    }
}

From source file:org.kalypso.grid.TiffGeoGrid.java

private TiledImage createTIFF(final File imageFile, final int sizeX, final int sizeY) throws GeoGridException {
    try {/*from w w w  . j  av a  2 s .c o m*/
        /* Store the image file. */
        m_imageFile = imageFile;

        /* Create the TIFF, using the given dimensions. */
        if (!imageFile.exists()) {
            m_sizeX = sizeX;
            m_sizeY = sizeY;

            return TIFFUtilities.createTiff(DataBuffer.TYPE_FLOAT, sizeX, sizeY);
        }

        /* Create the input stream. */
        m_inputStream = new FileSeekableStream(imageFile);

        /* Load the TIFF. */
        final RenderedOp renderedOp = TIFFUtilities.loadTiff(m_inputStream);

        /* The dimensions should be automatically calculated. */
        m_sizeX = -1;
        m_sizeY = -1;

        return new TiledImage(renderedOp, false);
    } catch (final Exception ex) {
        throw new GeoGridException("Error while creating/loading the tiff image...", ex);
    }
}