Example usage for java.awt.image DataBuffer TYPE_DOUBLE

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

Introduction

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

Prototype

int TYPE_DOUBLE

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

Click Source Link

Document

Tag for double data.

Usage

From source file:nitf.imageio.NITFReader.java

@Override
public Raster readRaster(int imageIndex, ImageReadParam param) throws IOException {
    checkIndex(imageIndex);//  w  w w.  j a  va  2s  .co  m

    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//from  w  ww  .jav  a  2  s .com
 * @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.esa.nest.gpf.ERSCalibrator.java

private static RenderedImage createRenderedImage(final double[] array, final int width, final int height) {

    // create rendered image with demension being width by height
    final SampleModel sampleModel = RasterFactory.createBandedSampleModel(DataBuffer.TYPE_DOUBLE, width, height,
            1);/*  ww w  .j av  a  2s .co m*/
    final ColorModel colourModel = PlanarImage.createColorModel(sampleModel);
    final DataBufferDouble dataBuffer = new DataBufferDouble(array, array.length);
    final WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, dataBuffer, new Point(0, 0));
    return new BufferedImage(colourModel, raster, false, new Hashtable());
}

From source file:org.esa.nest.gpf.GCPSelectionOp.java

private static RenderedImage createRenderedImage(final double[] array, final int w, final int h) {

    // create rendered image with demension being width by height
    final SampleModel sampleModel = RasterFactory.createBandedSampleModel(DataBuffer.TYPE_DOUBLE, w, h, 1);
    final ColorModel colourModel = PlanarImage.createColorModel(sampleModel);
    final DataBufferDouble dataBuffer = new DataBufferDouble(array, array.length);
    final WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, dataBuffer, new Point(0, 0));

    return new BufferedImage(colourModel, raster, false, new Hashtable());
}

From source file:org.esa.nest.gpf.oceantools.WindFieldEstimationOp.java

private static RenderedImage createRenderedImage(double[] array, int width, int height) {

    // create rendered image with demension being width by height
    final SampleModel sampleModel = RasterFactory.createBandedSampleModel(DataBuffer.TYPE_DOUBLE, width, height,
            1);/*from   w w w  .  j  av  a  2  s  .c  om*/
    final ColorModel colourModel = PlanarImage.createColorModel(sampleModel);
    final DataBufferDouble dataBuffer = new DataBufferDouble(array, array.length);
    final WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, dataBuffer, new Point(0, 0));
    return new BufferedImage(colourModel, raster, false, new Hashtable());
}

From source file:org.esa.s1tbx.insar.gpf.coregistration.CrossCorrelationOp.java

private static RenderedImage createRenderedImage(final double[] array, final int w, final int h) {

    // create rendered image with dimension being width by height
    final SampleModel sampleModel = RasterFactory.createBandedSampleModel(DataBuffer.TYPE_DOUBLE, w, h, 1);
    final ColorModel colourModel = PlanarImage.createColorModel(sampleModel);
    final DataBufferDouble dataBuffer = new DataBufferDouble(array, array.length);
    final WritableRaster raster = RasterFactory.createWritableRaster(sampleModel, dataBuffer, new Point(0, 0));

    return new BufferedImage(colourModel, raster, false, new Hashtable());
}

From source file:org.freecine.filmscan.ScanStrip.java

/**
 Try to find perforation corners using (modified) Hough transform. After the
 hough transform, matching pairs of top and bottom corners are found and
 clustered into pointClusterws list./*w w  w. ja  v a2s  .  c om*/
 */
void houghTransform() {

    // Siebel transform of stripImage
    KernelJAI sxKernel = new KernelJAI(3, 3,
            new float[] { -1.0f, 0.0f, 1.0f, -2.0f, 0.0f, 2.0f, -1.0f, 0.0f, 1.0f });
    KernelJAI syKernel = new KernelJAI(3, 3,
            new float[] { -1.0f, -2.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 2.0f, 1.0f });

    RenderedImage dblImg = FormatDescriptor.create(stripImage, DataBuffer.TYPE_DOUBLE, null);
    RenderedImage sxImg = ConvolveDescriptor.create(dblImg, sxKernel, null);
    RenderedImage syImg = ConvolveDescriptor.create(dblImg, syKernel, null);

    SampleModel sm = sxImg.getSampleModel();
    int nbands = sm.getNumBands();
    double[] sxPixel = new double[nbands];
    double[] syPixel = new double[nbands];

    /*
     We are interested only in the left side of the strip as the 
     perforations are there
     */
    Rectangle perfArea = new Rectangle(0, 0, stripImage.getWidth() / 4, stripImage.getHeight());
    RectIter sxIter = RectIterFactory.create(sxImg, perfArea);
    RectIter syIter = RectIterFactory.create(syImg, perfArea);

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

    /*
     We use 2 accumulators - one for detecting the upper right corner,
     one for lower right corner. As the original is huge and the detaile we 
     are looking for are tiny, we use a sliding window that stores only the 
     relevant part of accumulator.
     */
    int accumHeight = (int) maxCornerRadius + 2;
    int[][] startAccum = new int[(int) (maxCornerRadius - minCornerRadius)][width * accumHeight];
    int[][] endAccum = new int[(int) (maxCornerRadius - minCornerRadius)][width * accumHeight];

    List<Point> startCorners = new ArrayList<Point>();
    List<Point> endCorners = new ArrayList<Point>();
    int y = 0;
    int maxVal = 0;
    if (analysisListener != null) {
        analysisListener.scanAnalysisProgress(0, height);
    }
    while (!sxIter.nextLineDone() && !syIter.nextLineDone()) {
        if (y % 1000 == 0 && y > 0) {
            System.out.println("" + y + " lines analyzed");
        }
        sxIter.startPixels();
        syIter.startPixels();
        int x = 0;
        while (!sxIter.nextPixelDone() && !syIter.nextPixelDone()) {
            sxIter.getPixel(sxPixel);
            syIter.getPixel(syPixel);
            double isq = sxPixel[0] * sxPixel[0] + syPixel[0] * syPixel[0];
            if (isq > EDGE_MIN_GRADIENT * EDGE_MIN_GRADIENT) {
                // This seems like a border
                if (syPixel[0] <= 0 && sxPixel[0] >= 0) {
                    // Upper right corner candidate
                    double intensity = Math.sqrt(isq);
                    for (double r = minCornerRadius; r < maxCornerRadius; r += 1.0) {
                        double cx = (double) x - r * sxPixel[0] / intensity;
                        double cy = (double) y - r * syPixel[0] / intensity;
                        if (cx > 0.0) {
                            int accumLine = (int) cy % accumHeight;
                            startAccum[(int) (r - minCornerRadius)][(int) cx + width * accumLine]++;
                            if (startAccum[(int) (r - minCornerRadius)][(int) cx
                                    + width * accumLine] > maxVal) {
                                maxVal = startAccum[(int) (r - minCornerRadius)][(int) cx + width * accumLine];
                            }
                        }
                    }
                }
                if (syPixel[0] >= 0 && sxPixel[0] >= 0) {
                    // Lower right corner candidate
                    double intensity = Math.sqrt(isq);
                    for (double r = minCornerRadius; r < maxCornerRadius; r += 1.0) {
                        double cx = (double) x - r * sxPixel[0] / intensity;
                        double cy = (double) y - r * syPixel[0] / intensity;
                        if (cx > 0.0 && cy > 0.0) {
                            int accumLine = (int) cy % accumHeight;
                            endAccum[(int) (r - minCornerRadius)][(int) cx + width * accumLine]++;
                            if (endAccum[(int) (r - minCornerRadius)][(int) cx + width * accumLine] > maxVal) {
                                maxVal = endAccum[(int) (r - minCornerRadius)][(int) cx + width * accumLine];
                            }
                        }
                    }
                }
            }
            x++;
        }
        y++;

        /*
         1 line processed - check if there are corner candidates in the 
         accumulator line we are going to overwrite
         */
        int y2 = y - accumHeight;
        int l = y % accumHeight;
        if (y2 > 0) {
            for (int n = 0; n < perfArea.getWidth(); n++) {
                for (int r = 0; r < (int) (maxCornerRadius - minCornerRadius); r++) {
                    if (startAccum[r][n + width * l] >= CORNER_MIN_HOUGH) {
                        // Is this a local maxima?
                        int val = startAccum[r][n + width * l];
                        if (val == getLocalMaxima(startAccum, r, n, y, width)) {
                            startCorners.add(new Point(n, y));
                            System.out.println(String.format("Found corner, quality = %d, r = %d, (%d, %d)",
                                    val, r, n, y));
                            // imageDataSingleArray[n+width*y] = (byte) 0xff;
                        }
                    }
                    if (endAccum[r][n + width * l] > CORNER_MIN_HOUGH) {
                        // Is this a local maxima?
                        int val = endAccum[r][n + width * l];
                        if (val == getLocalMaxima(endAccum, r, n, y2, width)) {
                            endCorners.add(new Point(n, y2));
                            System.out.println(String.format("Found end corner, quality = %d, r = %d, (%d, %d)",
                                    val, r, n, y2));
                            // imageDataSingleArray[n+width*y2] = (byte) 0x80;
                        }
                    }
                }
            }
        }
        // Zero the line just analyzed - it will be reused for the next line
        for (int n = 0; n < perfArea.getWidth(); n++) {
            for (int r = 0; r < (int) (maxCornerRadius - minCornerRadius); r++) {
                startAccum[r][n + width * (y % accumHeight)] = 0;
                endAccum[r][n + width * (y % accumHeight)] = 0;
            }
        }
        if ((y % 100 == 1) && analysisListener != null) {
            analysisListener.scanAnalysisProgress(y - 1, height);
        }
    }

    if (analysisListener != null) {
        analysisListener.scanAnalysisProgress(height, height);
    }

    /*
     Find perforations, i.e. pairs of start and end corners that are within
     the specified range from each other
     */
    for (Point sp : startCorners) {
        for (Point ep : endCorners) {
            if (ep.y - sp.y > CC_MAX_DIST) {
                break;
            }
            if (Math.abs(ep.x - sp.x) < 10 && ep.y - sp.y > CC_MIN_DIST) {
                Perforation p = new Perforation();
                p.x = (ep.x + sp.x) >> 1;
                p.y = (ep.y + sp.y) >> 1;
                // imageDataSingleArray[p.x+width*p.y] = (byte) 0x40;
                addPointToCluster(p.x, p.y);
            }
        }
    }

    System.out.println(String.format("%d clusters:", pointClusters.size()));
    for (PointCluster c : pointClusters) {
        System.out.println(
                String.format("  (%d, %d) %d points", c.getCentroidX(), c.getCentroidY(), c.getPointCount()));
        // imageDataSingleArray[c.getCentroidX()+width*c.getCentroidY()] = (byte) 0xff;
    }

}

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

/**
 * Builds a new tile, eventually recycling the data array backing it
 *///from ww w.j av  a2 s .c  o m
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 va2s  .  c  o m
@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  w  w  w .j a va 2  s . c o m*/
@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;
}