Search in sources :

Example 1 with Band

use of org.gdal.gdal.Band in project imageio-ext by geosolutions-it.

the class GDALCommonIIOImageMetadata method setMembers.

/**
 * Set all the fields of the common metadata object.
 *
 * @param dataset
 *                the <code>Dataset</code> which will be used for the
 *                initialization
 * @return <code>true</code> if the initialization was successfully
 *         completed. <code>false</code> if some field wasn't properly
 *         initialized
 */
private boolean setMembers(Dataset dataset) {
    // Retrieving raster properties
    setWidth(dataset.getRasterXSize());
    setHeight(dataset.getRasterYSize());
    // Retrieving block size
    final int[] xBlockSize = new int[1];
    final int[] yBlockSize = new int[1];
    // Remember: RasterBand numeration starts from 1
    Band rband = null;
    try {
        rband = dataset.GetRasterBand(1);
        rband.GetBlockSize(xBlockSize, yBlockSize);
        final int tileHeight = yBlockSize[0];
        final int tileWidth = xBlockSize[0];
        setTileHeight(tileHeight);
        setTileWidth(tileWidth);
        if (((long) tileHeight) * ((long) tileWidth) > Integer.MAX_VALUE)
            performTileSizeTuning(dataset);
        // /////////////////////////////////////////////////////////////////
        // 
        // Getting dataset main properties
        // 
        // /////////////////////////////////////////////////////////////////
        final int numBands = dataset.getRasterCount();
        setNumBands(numBands);
        if (numBands <= 0)
            return false;
        // final int xsize = dataset.getRasterXSize();
        // final int ysize = dataset.getRasterYSize();
        // If the image is very big, its size expressed as the number of
        // bytes needed to store pixels, may be a negative number
        final int tileSize = tileWidth * tileHeight * numBands * (gdal.GetDataTypeSize(rband.getDataType()) / 8);
        // bands variables
        final int[] banks = new int[numBands];
        final int[] offsetsR = new int[numBands];
        final Double[] noDataValues = new Double[numBands];
        final Double[] scales = new Double[numBands];
        final Double[] offsets = new Double[numBands];
        final Double[] minimums = new Double[numBands];
        final Double[] maximums = new Double[numBands];
        final int[] numOverviews = new int[numBands];
        final int[] colorInterpretations = new int[numBands];
        int buf_type = 0;
        Band pBand = null;
        // scanning bands
        final Double[] tempD = new Double[1];
        final int[] bandsOffset = new int[numBands];
        for (int band = 0; band < numBands; band++) {
            /* Bands are not 0-base indexed, so we must add 1 */
            try {
                pBand = dataset.GetRasterBand(band + 1);
                buf_type = pBand.getDataType();
                banks[band] = band;
                offsetsR[band] = 0;
                pBand.GetNoDataValue(tempD);
                noDataValues[band] = tempD[0];
                pBand.GetOffset(tempD);
                offsets[band] = tempD[0];
                pBand.GetScale(tempD);
                scales[band] = tempD[0];
                pBand.GetMinimum(tempD);
                minimums[band] = tempD[0];
                pBand.GetMaximum(tempD);
                maximums[band] = tempD[0];
                colorInterpretations[band] = pBand.GetRasterColorInterpretation();
                numOverviews[band] = pBand.GetOverviewCount();
                bandsOffset[band] = band;
            } finally {
                if (pBand != null) {
                    try {
                        // Closing the band
                        pBand.delete();
                    } catch (Throwable e) {
                        if (LOGGER.isLoggable(Level.FINEST))
                            LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        setNoDataValues(noDataValues);
        setScales(scales);
        setOffsets(offsets);
        setMinimums(minimums);
        setMaximums(maximums);
        setNumOverviews(numOverviews);
        setColorInterpretations(colorInterpretations);
        // /////////////////////////////////////////////////////////////////
        // 
        // Variable used to specify the data type for the storing samples
        // of the SampleModel
        // 
        // /////////////////////////////////////////////////////////////////
        int buffer_type = 0;
        if (buf_type == gdalconstConstants.GDT_Byte)
            buffer_type = DataBuffer.TYPE_BYTE;
        else if (buf_type == gdalconstConstants.GDT_UInt16)
            buffer_type = DataBuffer.TYPE_USHORT;
        else if (buf_type == gdalconstConstants.GDT_Int16)
            buffer_type = DataBuffer.TYPE_SHORT;
        else if ((buf_type == gdalconstConstants.GDT_Int32) || (buf_type == gdalconstConstants.GDT_UInt32))
            buffer_type = DataBuffer.TYPE_INT;
        else if (buf_type == gdalconstConstants.GDT_Float32)
            buffer_type = DataBuffer.TYPE_FLOAT;
        else if (buf_type == gdalconstConstants.GDT_Float64)
            buffer_type = DataBuffer.TYPE_DOUBLE;
        else
            return false;
        // //
        if (tileSize < 0)
            setSampleModel(new BandedSampleModel(buffer_type, tileWidth, tileHeight, tileWidth, banks, offsetsR));
        else
            setSampleModel(new PixelInterleavedSampleModel(buffer_type, tileWidth, tileHeight, numBands, tileWidth * numBands, bandsOffset));
        // //
        if (colorInterpretations[0] == gdalconstConstants.GCI_PaletteIndex) {
            ColorTable ct = null;
            try {
                ct = rband.GetRasterColorTable();
                IndexColorModel icm = ct.getIndexColorModel(gdal.GetDataTypeSize(buf_type));
                setColorModel(icm);
            } finally {
                if (ct != null) {
                    try {
                        // Closing the band
                        ct.delete();
                    } catch (Throwable e) {
                        if (LOGGER.isLoggable(Level.FINEST))
                            LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
                    }
                }
            }
        } else
            setColorModel(GDALUtilities.buildColorModel(getSampleModel()));
        if (getColorModel() == null || getSampleModel() == null)
            return false;
    } finally {
        if (rband != null) {
            try {
                // Closing the band
                rband.delete();
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINEST))
                    LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
            }
        }
    }
    return true;
}
Also used : PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) BandedSampleModel(java.awt.image.BandedSampleModel) ColorTable(org.gdal.gdal.ColorTable) Band(org.gdal.gdal.Band) IndexColorModel(java.awt.image.IndexColorModel)

Example 2 with Band

use of org.gdal.gdal.Band in project imageio-ext by geosolutions-it.

the class GDALImageReader method readDatasetRaster.

/**
 * Read data from the required region of the raster.
 *
 * @param destSM
 *                sample model for the image
 * @param dataset
 *                GDAL <code>Dataset</code> to read
 * @param srcRegion
 *                the source Region to be read
 * @param dstRegion
 *                the destination Region of the image read
 * @param selectedBands
 *                an array specifying the requested bands
 * @return the read <code>Raster</code>
 */
private Raster readDatasetRaster(SampleModel destSm, Dataset dataset, Rectangle srcRegion, Rectangle dstRegion, int[] selectedBands) throws IOException {
    SampleModel sampleModel = null;
    DataBuffer imgBuffer = null;
    Band pBand = null;
    try {
        int dstWidth = dstRegion.width;
        int dstHeight = dstRegion.height;
        int srcRegionXOffset = srcRegion.x;
        int srcRegionYOffset = srcRegion.y;
        int srcRegionWidth = srcRegion.width;
        int srcRegionHeight = srcRegion.height;
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("SourceRegion = " + srcRegion.toString());
        // Getting number of bands
        final int nBands = selectedBands != null ? selectedBands.length : destSm.getNumBands();
        int[] banks = new int[nBands];
        int[] offsets = new int[nBands];
        // setting the number of pixels to read
        final int pixels = dstWidth * dstHeight;
        int bufferType = 0, bufferSize = 0;
        int typeSizeInBytes = 0;
        // ////////////////////////////////////////////////////////////////////
        // 
        // -------------------------------------------------------------------
        // Raster Creation >>> Step 2: Data Read
        // -------------------------------------------------------------------
        // 
        // ////////////////////////////////////////////////////////////////////
        // NOTE: Bands are not 0-base indexed, so we must add 1
        pBand = dataset.GetRasterBand(1);
        // setting buffer properties
        bufferType = pBand.getDataType();
        typeSizeInBytes = gdal.GetDataTypeSize(bufferType) / 8;
        bufferSize = nBands * pixels * typeSizeInBytes;
        // splitBands = false -> I read n Bands at once.
        // splitBands = false -> I need to read 1 Band at a time.
        boolean splitBands = false;
        if (bufferSize < 0 || destSm instanceof BandedSampleModel) {
            // The number resulting from the product
            // "numBands*pixels*gdal.GetDataTypeSize(buf_type) / 8"
            // may be negative (A very high number which is not
            // "int representable")
            // In such a case, we will read 1 band at a time.
            bufferSize = pixels * typeSizeInBytes;
            splitBands = true;
        }
        int dataBufferType = -1;
        byte[][] byteBands = new byte[nBands][];
        for (int k = 0; k < nBands; k++) {
            // I quit the loop
            if (k > 0 && !splitBands)
                break;
            final byte[] dataBuffer = new byte[bufferSize];
            final int returnVal;
            if (!splitBands) {
                // I can read nBands at once.
                final int[] bandsMap = new int[nBands];
                if (selectedBands != null) {
                    for (int i = 0; i < nBands; i++) bandsMap[i] = selectedBands[i] + 1;
                } else {
                    for (int i = 0; i < nBands; i++) bandsMap[i] = i + 1;
                }
                returnVal = dataset.ReadRaster(srcRegionXOffset, srcRegionYOffset, srcRegionWidth, srcRegionHeight, dstWidth, dstHeight, bufferType, dataBuffer, bandsMap, nBands * typeSizeInBytes, dstWidth * nBands * typeSizeInBytes, typeSizeInBytes);
                byteBands[k] = dataBuffer;
            } else {
                // I need to read 1 band at a time.
                Band rBand = null;
                try {
                    rBand = dataset.GetRasterBand(k + 1);
                    returnVal = rBand.ReadRaster(srcRegionXOffset, srcRegionYOffset, srcRegionWidth, srcRegionHeight, dstWidth, dstHeight, bufferType, dataBuffer);
                    byteBands[k] = dataBuffer;
                } finally {
                    if (rBand != null) {
                        try {
                            // Closing the band
                            rBand.delete();
                        } catch (Throwable e) {
                            if (LOGGER.isLoggable(Level.FINEST))
                                LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
            if (returnVal == gdalconstConstants.CE_None) {
                if (!splitBands)
                    for (int band = 0; band < nBands; band++) {
                        banks[band] = band;
                        offsets[band] = band;
                    }
                else {
                    banks[k] = k;
                    offsets[k] = 0;
                }
            } else {
                // The read operation was not successfully computed.
                // Showing error messages.
                LOGGER.info(new StringBuilder("Last error: ").append(gdal.GetLastErrorMsg()).toString());
                LOGGER.info(new StringBuilder("Last error number: ").append(gdal.GetLastErrorNo()).toString());
                LOGGER.info(new StringBuilder("Last error type: ").append(gdal.GetLastErrorType()).toString());
                throw new RuntimeException(gdal.GetLastErrorMsg());
            }
        }
        // /////////////////////////////////////////////////////////////////////
        if (bufferType == gdalconstConstants.GDT_Byte) {
            if (!splitBands) {
                // final byte[] bytes = new byte[nBands * pixels];
                // bands[0].get(bytes, 0, nBands * pixels);
                imgBuffer = new DataBufferByte(byteBands[0], nBands * pixels);
            } else {
                // final byte[][] bytes = new byte[nBands][];
                // for (int i = 0; i < nBands; i++) {
                // //                    bytes[i] = new byte[pixels];
                // bands[i].get(bytes[i], 0, pixels);
                // }
                imgBuffer = new DataBufferByte(byteBands, pixels);
            }
            dataBufferType = DataBuffer.TYPE_BYTE;
        } else {
            ByteBuffer[] bands = new ByteBuffer[nBands];
            for (int k = 0; (splitBands && k < nBands) || (k < 1 && !splitBands); k++) {
                bands[k] = ByteBuffer.wrap(byteBands[k], 0, byteBands[k].length);
            }
            if (bufferType == gdalconstConstants.GDT_Int16 || bufferType == gdalconstConstants.GDT_UInt16) {
                if (!splitBands) {
                    // I get short values from the ByteBuffer using a view
                    // of the ByteBuffer as a ShortBuffer
                    // It is worth to create the view outside the loop.
                    short[] shorts = new short[nBands * pixels];
                    bands[0].order(ByteOrder.nativeOrder());
                    final ShortBuffer buff = bands[0].asShortBuffer();
                    buff.get(shorts, 0, nBands * pixels);
                    if (bufferType == gdalconstConstants.GDT_Int16)
                        imgBuffer = new DataBufferShort(shorts, nBands * pixels);
                    else
                        imgBuffer = new DataBufferUShort(shorts, nBands * pixels);
                } else {
                    short[][] shorts = new short[nBands][];
                    for (int i = 0; i < nBands; i++) {
                        shorts[i] = new short[pixels];
                        bands[i].order(ByteOrder.nativeOrder());
                        bands[i].asShortBuffer().get(shorts[i], 0, pixels);
                    }
                    if (bufferType == gdalconstConstants.GDT_Int16)
                        imgBuffer = new DataBufferShort(shorts, pixels);
                    else
                        imgBuffer = new DataBufferUShort(shorts, pixels);
                }
                if (bufferType == gdalconstConstants.GDT_UInt16)
                    dataBufferType = DataBuffer.TYPE_USHORT;
                else
                    dataBufferType = DataBuffer.TYPE_SHORT;
            } else if (bufferType == gdalconstConstants.GDT_Int32 || bufferType == gdalconstConstants.GDT_UInt32) {
                if (!splitBands) {
                    // I get int values from the ByteBuffer using a view
                    // of the ByteBuffer as an IntBuffer
                    // It is worth to create the view outside the loop.
                    int[] ints = new int[nBands * pixels];
                    bands[0].order(ByteOrder.nativeOrder());
                    final IntBuffer buff = bands[0].asIntBuffer();
                    buff.get(ints, 0, nBands * pixels);
                    imgBuffer = new DataBufferInt(ints, nBands * pixels);
                } else {
                    int[][] ints = new int[nBands][];
                    for (int i = 0; i < nBands; i++) {
                        ints[i] = new int[pixels];
                        bands[i].order(ByteOrder.nativeOrder());
                        bands[i].asIntBuffer().get(ints[i], 0, pixels);
                    }
                    imgBuffer = new DataBufferInt(ints, pixels);
                }
                dataBufferType = DataBuffer.TYPE_INT;
            } else if (bufferType == gdalconstConstants.GDT_Float32) {
                if (!splitBands) {
                    // I get float values from the ByteBuffer using a view
                    // of the ByteBuffer as a FloatBuffer
                    // It is worth to create the view outside the loop.
                    float[] floats = new float[nBands * pixels];
                    bands[0].order(ByteOrder.nativeOrder());
                    final FloatBuffer buff = bands[0].asFloatBuffer();
                    buff.get(floats, 0, nBands * pixels);
                    imgBuffer = new DataBufferFloat(floats, nBands * pixels);
                } else {
                    float[][] floats = new float[nBands][];
                    for (int i = 0; i < nBands; i++) {
                        floats[i] = new float[pixels];
                        bands[i].order(ByteOrder.nativeOrder());
                        bands[i].asFloatBuffer().get(floats[i], 0, pixels);
                    }
                    imgBuffer = new DataBufferFloat(floats, pixels);
                }
                dataBufferType = DataBuffer.TYPE_FLOAT;
            } else if (bufferType == gdalconstConstants.GDT_Float64) {
                if (!splitBands) {
                    // I get double values from the ByteBuffer using a view
                    // of the ByteBuffer as a DoubleBuffer
                    // It is worth to create the view outside the loop.
                    double[] doubles = new double[nBands * pixels];
                    bands[0].order(ByteOrder.nativeOrder());
                    final DoubleBuffer buff = bands[0].asDoubleBuffer();
                    buff.get(doubles, 0, nBands * pixels);
                    imgBuffer = new DataBufferDouble(doubles, nBands * pixels);
                } else {
                    double[][] doubles = new double[nBands][];
                    for (int i = 0; i < nBands; i++) {
                        doubles[i] = new double[pixels];
                        bands[i].order(ByteOrder.nativeOrder());
                        bands[i].asDoubleBuffer().get(doubles[i], 0, pixels);
                    }
                    imgBuffer = new DataBufferDouble(doubles, pixels);
                }
                dataBufferType = DataBuffer.TYPE_DOUBLE;
            } else {
                // TODO: Handle more cases if needed. Show the name of the type
                // instead of the numeric value.
                LOGGER.info("The specified data type is actually unsupported: " + bufferType);
            }
        }
        // TODO: Fix this in compliance with the specified destSampleModel
        if (splitBands)
            sampleModel = new BandedSampleModel(dataBufferType, dstWidth, dstHeight, dstWidth, banks, offsets);
        else
            sampleModel = new PixelInterleavedSampleModel(dataBufferType, dstWidth, dstHeight, nBands, dstWidth * nBands, offsets);
    } finally {
        if (pBand != null) {
            try {
                // Closing the band
                pBand.delete();
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
            }
        }
    }
    // dstRegion.x, dstRegion.y));
    return Raster.createWritableRaster(sampleModel, imgBuffer, null);
}
Also used : DataBufferDouble(java.awt.image.DataBufferDouble) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) Band(org.gdal.gdal.Band) FloatBuffer(java.nio.FloatBuffer) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) DataBufferShort(java.awt.image.DataBufferShort) BandedSampleModel(java.awt.image.BandedSampleModel) DataBufferUShort(java.awt.image.DataBufferUShort) DataBuffer(java.awt.image.DataBuffer) DoubleBuffer(java.nio.DoubleBuffer) ByteBuffer(java.nio.ByteBuffer) SampleModel(java.awt.image.SampleModel) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) BandedSampleModel(java.awt.image.BandedSampleModel) IntBuffer(java.nio.IntBuffer) DataBufferFloat(java.awt.image.DataBufferFloat) ShortBuffer(java.nio.ShortBuffer)

Example 3 with Band

use of org.gdal.gdal.Band in project imageio-ext by geosolutions-it.

the class GDALImageWriter method setMetadata.

/**
 * Set all the metadata available in the imageMetadata
 * <code>IIOMetadata</code> instance
 *
 * @param dataset
 *                the dataset on which to set metadata and properties
 * @param imageMetadata
 *                an instance of a {@link GDALCommonIIOImageMetadata}
 *                containing metadata
 */
private void setMetadata(Dataset dataset, GDALCommonIIOImageMetadata imageMetadata) {
    // TODO: which metadata should be copied in the dataset?
    // Should width, height and similar properties to be copied?
    // //
    // 
    // Setting GeoTransformation
    // 
    // //
    final double[] geoTransformation = imageMetadata.getGeoTransformation();
    if (geoTransformation != null)
        dataset.SetGeoTransform(geoTransformation);
    // //
    // 
    // Setting Projection
    // 
    // //
    final String projection = imageMetadata.getProjection();
    if (projection != null && projection.trim().length() != 0)
        dataset.SetProjection(projection);
    // //
    // 
    // Setting GCPs
    // 
    // //
    final int gcpNum = imageMetadata.getGcpNumber();
    if (gcpNum != 0) {
        final String gcpProj = imageMetadata.getGcpProjection();
        List gcps = imageMetadata.getGCPs();
    // TODO: Fix getGCPs access in SWIG's Java Bindings
    // TODO: set GCPs. Not all dataset support GCPs settings
    // dataset.SetGCPs(1, gcps, gcpProj);
    }
    // //
    // 
    // Setting bands values
    // 
    // //
    final int nBands = imageMetadata.getNumBands();
    for (int i = 0; i < nBands; i++) {
        final Band band = dataset.GetRasterBand(i + 1);
        final int colorInterpretation = imageMetadata.getColorInterpretations(i);
        band.SetRasterColorInterpretation(colorInterpretation);
        if (i == 0 && nBands == 1) {
            // //
            if (colorInterpretation == gdalconstConstants.GCI_PaletteIndex) {
                ColorModel cm = imageMetadata.getColorModel();
                if (cm instanceof IndexColorModel) {
                    IndexColorModel icm = (IndexColorModel) cm;
                    // //
                    // 
                    // Setting color table
                    // 
                    // //
                    final int size = icm.getMapSize();
                    ColorTable ct = new ColorTable(gdalconstConstants.GPI_RGB);
                    int j = 0;
                    for (; j < size; j++) ct.SetColorEntry(j, new Color(icm.getRGB(j)));
                    band.SetRasterColorTable(ct);
                }
            }
        }
        try {
            final double noData = imageMetadata.getNoDataValue(i);
            if (!Double.isNaN(noData))
                band.SetNoDataValue(noData);
        } catch (IllegalArgumentException iae) {
        // NoDataValue not found or wrong bandIndex specified. Go on
        }
    }
    // //
    // 
    // Setting metadata
    // 
    // TODO: Requires SWIG bindings extending since an HashTable as
    // parameter crashes the JVM
    // 
    // //
    final List<String> domains = imageMetadata.getGdalMetadataDomainsList();
    final int nDomains = domains.size();
    for (int i = 0; i < nDomains; i++) {
        final String domain = (String) domains.get(i);
        Map metadataMap = imageMetadata.getGdalMetadataDomain(domain);
        if (metadataMap != null) {
            Iterator<String> keysIt = metadataMap.keySet().iterator();
            while (keysIt.hasNext()) {
                final String key = keysIt.next();
                final String value = (String) metadataMap.get(key);
                dataset.SetMetadataItem(key, value, domain);
            }
        }
    }
}
Also used : ColorTable(org.gdal.gdal.ColorTable) Color(java.awt.Color) Band(org.gdal.gdal.Band) IndexColorModel(java.awt.image.IndexColorModel) ColorModel(java.awt.image.ColorModel) List(java.util.List) Map(java.util.Map) IndexColorModel(java.awt.image.IndexColorModel)

Example 4 with Band

use of org.gdal.gdal.Band in project com.revolsys.open by revolsys.

the class Gdal method getBufferedImage.

/**
 * <p>
 * Convert the overview raster from {@link Dataset} to a
 * {@link BufferedImage} . The raster will be clipped to the
 * sourceOffsetX,sourceOffsetY -> sourceWidth, sourceHeight rectangle. The
 * clip rectangle will be adjusted to fit inside the bounds of the source
 * image. The result image will scaled to the dimensions of targetWidth,
 * targetHeight.
 * </p>
 *
 * @param dataset
 *            The image dataset.
 * @param overviewIndex
 *            The index of the overview raster data. Use -1 for the whole
 *            image.
 * @param sourceOffsetX
 *            The x location of the clip rectangle.
 * @param sourceOffsetY
 *            The y location of the clip rectangle.
 * @param sourceWidth
 *            The width of the clip rectangle. Use -1 to auto calculate.
 * @param sourceHeight
 *            The height of the clip rectangle. Use -1 to auto calculate.
 * @param targetWidth
 *            The width of the result image. Use -1 to auto calculate.
 * @param targetHeight
 *            The height of the result image. Use -1 to auto calculate.
 * @return The buffered image.
 */
public static BufferedImage getBufferedImage(final Dataset dataset, final int overviewIndex, int sourceOffsetX, int sourceOffsetY, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight) {
    synchronized (dataset) {
        final int bandCount = dataset.getRasterCount();
        final ByteBuffer[] bandData = new ByteBuffer[bandCount];
        final int[] banks = new int[bandCount];
        final int[] offsets = new int[bandCount];
        int pixels = 0;
        int bandDataType = 0;
        int rasterColorInterpretation = -1;
        ColorTable rasterColorTable = null;
        for (int bandIndex = 0; bandIndex < bandCount; bandIndex++) {
            final Band band = dataset.GetRasterBand(bandIndex + 1);
            try {
                Band overviewBand;
                if (overviewIndex == -1) {
                    overviewBand = band;
                } else {
                    overviewBand = band.GetOverview(overviewIndex);
                }
                try {
                    if (rasterColorTable == null) {
                        rasterColorTable = band.GetRasterColorTable();
                        rasterColorInterpretation = band.GetRasterColorInterpretation();
                        bandDataType = band.getDataType();
                        final int overviewWidth = overviewBand.getXSize();
                        final int overviewHeight = overviewBand.getYSize();
                        if (sourceOffsetX < 0) {
                            sourceOffsetX = 0;
                        }
                        if (sourceOffsetY < 0) {
                            sourceOffsetY = 0;
                        }
                        if (sourceOffsetX >= overviewWidth || sourceOffsetY >= overviewHeight) {
                            return new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
                        }
                        if (sourceWidth < 0) {
                            sourceWidth = overviewWidth;
                        }
                        if (sourceOffsetX + sourceWidth > overviewWidth) {
                            sourceWidth = overviewWidth - sourceOffsetX;
                        }
                        if (targetWidth < 0) {
                            targetWidth = sourceWidth;
                        }
                        if (sourceHeight < 0) {
                            sourceHeight = overviewHeight;
                        }
                        if (sourceOffsetY + sourceHeight > overviewHeight) {
                            sourceHeight = overviewHeight - sourceOffsetY;
                        }
                        if (targetHeight < 0) {
                            targetHeight = sourceHeight;
                        }
                        pixels = targetWidth * targetHeight;
                    }
                    if (pixels > 0 && sourceHeight > 0 && sourceWidth > 0) {
                        final int bufferSize = pixels * gdal.GetDataTypeSize(bandDataType) / 8;
                        final ByteBuffer data = ByteBuffer.allocateDirect(bufferSize);
                        data.order(ByteOrder.nativeOrder());
                        final int result = overviewBand.ReadRaster_Direct(sourceOffsetX, sourceOffsetY, sourceWidth, sourceHeight, targetWidth, targetHeight, bandDataType, data);
                        if (result == gdalconstConstants.CE_None) {
                            bandData[bandIndex] = data;
                        } else {
                            throw new RuntimeException("Error converting image");
                        }
                    } else {
                        return new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
                    }
                    banks[bandIndex] = bandIndex;
                    offsets[bandIndex] = 0;
                } finally {
                    overviewBand.delete();
                }
            } finally {
                band.delete();
            }
        }
        DataBuffer imageBuffer = null;
        SampleModel sampleModel = null;
        int dataType = 0;
        int dataBufferType = 0;
        if (bandDataType == gdalconstConstants.GDT_Byte) {
            final byte[][] bytes = new byte[bandCount][];
            for (int bandIndex = 0; bandIndex < bandCount; bandIndex++) {
                bytes[bandIndex] = new byte[pixels];
                bandData[bandIndex].get(bytes[bandIndex]);
            }
            imageBuffer = new DataBufferByte(bytes, pixels);
            dataBufferType = DataBuffer.TYPE_BYTE;
            sampleModel = new BandedSampleModel(dataBufferType, targetWidth, targetHeight, targetWidth, banks, offsets);
            dataType = rasterColorInterpretation == gdalconstConstants.GCI_PaletteIndex ? BufferedImage.TYPE_BYTE_INDEXED : BufferedImage.TYPE_BYTE_GRAY;
        } else if (bandDataType == gdalconstConstants.GDT_Int16) {
            final short[][] shorts = new short[bandCount][];
            for (int bandIndex = 0; bandIndex < bandCount; bandIndex++) {
                shorts[bandIndex] = new short[pixels];
                bandData[bandIndex].asShortBuffer().get(shorts[bandIndex]);
            }
            imageBuffer = new DataBufferShort(shorts, pixels);
            dataBufferType = DataBuffer.TYPE_USHORT;
            sampleModel = new BandedSampleModel(dataBufferType, targetWidth, targetHeight, targetWidth, banks, offsets);
            dataType = BufferedImage.TYPE_USHORT_GRAY;
        } else if (bandDataType == gdalconstConstants.GDT_Int32) {
            final int[][] ints = new int[bandCount][];
            for (int bandIndex = 0; bandIndex < bandCount; bandIndex++) {
                ints[bandIndex] = new int[pixels];
                bandData[bandIndex].asIntBuffer().get(ints[bandIndex]);
            }
            imageBuffer = new DataBufferInt(ints, pixels);
            dataBufferType = DataBuffer.TYPE_INT;
            sampleModel = new BandedSampleModel(dataBufferType, targetWidth, targetHeight, targetWidth, banks, offsets);
            dataType = BufferedImage.TYPE_CUSTOM;
        }
        final WritableRaster raster = Raster.createWritableRaster(sampleModel, imageBuffer, null);
        BufferedImage image = null;
        ColorModel colorModel = null;
        if (rasterColorInterpretation == gdalconstConstants.GCI_PaletteIndex) {
            dataType = BufferedImage.TYPE_BYTE_INDEXED;
            colorModel = rasterColorTable.getIndexColorModel(gdal.GetDataTypeSize(bandDataType));
            image = new BufferedImage(colorModel, raster, false, null);
        } else {
            ColorSpace colorSpace = null;
            if (bandCount > 2) {
                colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
                colorModel = new ComponentColorModel(colorSpace, false, false, Transparency.OPAQUE, dataBufferType);
                image = new BufferedImage(colorModel, raster, true, null);
            } else {
                image = new BufferedImage(targetWidth, targetHeight, dataType);
                image.setData(raster);
            }
        }
        return image;
    }
}
Also used : ColorTable(org.gdal.gdal.ColorTable) ColorSpace(java.awt.color.ColorSpace) ComponentColorModel(java.awt.image.ComponentColorModel) Band(org.gdal.gdal.Band) DataBufferInt(java.awt.image.DataBufferInt) DataBufferByte(java.awt.image.DataBufferByte) ByteBuffer(java.nio.ByteBuffer) BufferedImage(java.awt.image.BufferedImage) DataBufferShort(java.awt.image.DataBufferShort) SampleModel(java.awt.image.SampleModel) BandedSampleModel(java.awt.image.BandedSampleModel) BandedSampleModel(java.awt.image.BandedSampleModel) WritableRaster(java.awt.image.WritableRaster) ComponentColorModel(java.awt.image.ComponentColorModel) ColorModel(java.awt.image.ColorModel) DataBuffer(java.awt.image.DataBuffer)

Aggregations

Band (org.gdal.gdal.Band)4 BandedSampleModel (java.awt.image.BandedSampleModel)3 ColorTable (org.gdal.gdal.ColorTable)3 ColorModel (java.awt.image.ColorModel)2 DataBuffer (java.awt.image.DataBuffer)2 DataBufferByte (java.awt.image.DataBufferByte)2 DataBufferInt (java.awt.image.DataBufferInt)2 DataBufferShort (java.awt.image.DataBufferShort)2 IndexColorModel (java.awt.image.IndexColorModel)2 PixelInterleavedSampleModel (java.awt.image.PixelInterleavedSampleModel)2 SampleModel (java.awt.image.SampleModel)2 ByteBuffer (java.nio.ByteBuffer)2 Color (java.awt.Color)1 ColorSpace (java.awt.color.ColorSpace)1 BufferedImage (java.awt.image.BufferedImage)1 ComponentColorModel (java.awt.image.ComponentColorModel)1 DataBufferDouble (java.awt.image.DataBufferDouble)1 DataBufferFloat (java.awt.image.DataBufferFloat)1 DataBufferUShort (java.awt.image.DataBufferUShort)1 WritableRaster (java.awt.image.WritableRaster)1