Search in sources :

Example 1 with Dataset

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

the class GdalImage method drawImage.

@Override
public void drawImage(final Graphics2D graphics, final BoundingBox viewBoundingBox, final int viewWidth, final int viewHeight, final boolean useTransform, final Object interpolationMethod) {
    try {
        final Dataset dataset = getDataset();
        final BoundingBox imageBoundingBox = getBoundingBox();
        final BoundingBox clipBoundingBox = viewBoundingBox.intersection(imageBoundingBox);
        final double scaleFactor = viewWidth / viewBoundingBox.getWidth();
        final double clipModelWidth = clipBoundingBox.getWidth();
        final int targetWidth = (int) Math.ceil(clipModelWidth * scaleFactor);
        final double clipModelHeight = clipBoundingBox.getHeight();
        final int targetHeight = (int) Math.ceil(clipModelHeight * scaleFactor);
        int bestOverviewIdx = -1;
        int srcWidth = getImageWidth();
        final double clipResolution = Math.abs(clipBoundingBox.getHeight() / targetHeight);
        final List<Dimension> overviewSizes = getOverviewSizes();
        for (int i = 0; i < overviewSizes.size(); i++) {
            final Dimension overviewSize = overviewSizes.get(i);
            final int width = overviewSize.width;
            final int height = overviewSize.height;
            if (0 != height && 0 != width) {
                final double overviewResolution = Math.abs(imageBoundingBox.getHeight() / height);
                if (overviewResolution <= clipResolution) {
                    bestOverviewIdx = i;
                    srcWidth = width;
                }
            }
        }
        final double scale = srcWidth / imageBoundingBox.getWidth();
        final int clipXoff = (int) Math.floor((clipBoundingBox.getMinX() - imageBoundingBox.getMinX()) * scale);
        final int clipYoff = (int) Math.floor((imageBoundingBox.getMaxY() - clipBoundingBox.getMaxY()) * scale);
        final int clipWidth = (int) Math.ceil(clipModelWidth * scale);
        final int clipHeight = (int) Math.ceil(clipModelHeight * scale);
        final BufferedImage bufferedImage = Gdal.getBufferedImage(dataset, bestOverviewIdx, clipXoff, clipYoff, clipWidth, clipHeight, targetWidth, targetHeight);
        super.drawRenderedImage(bufferedImage, clipBoundingBox, graphics, viewBoundingBox, viewWidth, useTransform, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    } catch (final Throwable e) {
        e.printStackTrace();
    }
}
Also used : Dataset(org.gdal.gdal.Dataset) BoundingBox(com.revolsys.geometry.model.BoundingBox) Dimension(java.awt.Dimension) BufferedImage(java.awt.image.BufferedImage)

Example 2 with Dataset

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

the class GDALImageReader method read.

/**
 * Read the raster and returns a <code>BufferedImage</code>
 *
 * @param imageIndex
 *                the index of the image to be retrieved.
 * @param param
 *                an <code>ImageReadParam</code> used to control the
 *                reading process, or <code>null</code>. Actually,
 *                setting a destinationType allows to specify the number of
 *                bands in the destination image.
 *
 * @return the desired portion of the image as a <code>BufferedImage</code>
 * @throws IllegalArgumentException
 *                 if <code>param</code> contains an invalid specification
 *                 of a source and/or destination band subset or of a
 *                 destination image.
 * @throws IOException
 *                 if an error occurs when acquiring access to the
 *                 underlying datasource
 */
public BufferedImage read(final int imageIndex, final ImageReadParam param) throws IOException {
    // //
    // 
    // Retrieving the requested dataset
    // 
    // //
    final GDALCommonIIOImageMetadata item = getDatasetMetadata(imageIndex);
    int width = item.getWidth();
    int height = item.getHeight();
    final Dataset originalDataset = datasetsMap.get(item.getDatasetName());
    if (originalDataset == null)
        throw new IOException("Error while acquiring the input dataset " + item.getDatasetName());
    Dataset dataset = originalDataset;
    Dataset warpedDataset = null;
    try {
        if (param instanceof GDALImageReadParam) {
            GDALImageReadParam gdalImageReadParam = (GDALImageReadParam) param;
            // Check for source != destination
            String sourceWkt = dataset.GetProjection();
            String destinationWkt = gdalImageReadParam.getDestinationWkt();
            SpatialReference sourceReference = new SpatialReference(sourceWkt);
            SpatialReference destinationReference = new SpatialReference(destinationWkt);
            // lets warp the image using GDAL.
            if (sourceReference.IsSame(destinationReference) == 0) {
                dataset = gdal.AutoCreateWarpedVRT(dataset, dataset.GetProjection(), destinationWkt, gdalImageReadParam.getResampleAlgorithm().getGDALResampleAlgorithm(), gdalImageReadParam.getMaxError());
                warpedDataset = dataset;
                // width and height may have changed from original metadata
                width = warpedDataset.getRasterXSize();
                height = warpedDataset.getRasterYSize();
            }
        }
        final SampleModel itemSampleModel = item.getSampleModel();
        int itemNBands = itemSampleModel.getNumBands();
        int nDestBands;
        BufferedImage bi = null;
        final ImageReadParam imageReadParam;
        if (param == null)
            imageReadParam = getDefaultReadParam();
        else
            imageReadParam = param;
        // //
        // 
        // First, check for a specified ImageTypeSpecifier
        // 
        // //
        ImageTypeSpecifier imageType = imageReadParam.getDestinationType();
        SampleModel destSampleModel = null;
        if (imageType != null) {
            destSampleModel = imageType.getSampleModel();
            nDestBands = destSampleModel.getNumBands();
        } else {
            bi = imageReadParam.getDestination();
            if (bi != null)
                nDestBands = bi.getSampleModel().getNumBands();
            else
                nDestBands = itemNBands;
        }
        // //
        // 
        // Second, bands settings check
        // 
        // //
        checkReadParamBandSettings(imageReadParam, itemNBands, nDestBands);
        int[] srcBands = imageReadParam.getSourceBands();
        // int[] destBands = imageReadParam.getDestinationBands();
        // 
        // //
        // 
        // Third, destination image check
        // 
        // //
        // if (bi != null && imageType == null) {
        // if ((srcBands == null) && (destBands == null)) {
        // SampleModel biSampleModel = bi.getSampleModel();
        // if (!bi.getColorModel().equals(item.getColorModel())
        // || biSampleModel.getDataType() != itemSampleModel
        // .getDataType())
        // throw new IllegalArgumentException(
        // "Provided destination image does not have a valid ColorModel or
        // SampleModel");
        // }
        // }
        // //
        // 
        // Computing regions of interest
        // 
        // //
        Rectangle srcRegion = new Rectangle(0, 0, 0, 0);
        Rectangle destRegion = new Rectangle(0, 0, 0, 0);
        computeRegions(imageReadParam, width, height, bi, srcRegion, destRegion);
        if (imageReadParam != null) {
            if (imageReadParam instanceof EnhancedImageReadParam) {
                final EnhancedImageReadParam eparam = (EnhancedImageReadParam) imageReadParam;
                final Rectangle dstRegion = eparam.getDestinationRegion();
                if (dstRegion != null) {
                    destRegion.height = dstRegion.height;
                    destRegion.width = dstRegion.width;
                }
            }
        }
        if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Source Region = " + srcRegion.toString());
            LOGGER.fine("Destination Region = " + destRegion.toString());
        }
        // 
        if (bi == null) {
            // //
            // 
            // No destination image has been specified.
            // Creating a new BufferedImage
            // 
            // //
            ColorModel cm;
            if (imageType == null) {
                cm = item.getColorModel();
                bi = new BufferedImage(cm, (WritableRaster) readDatasetRaster(item.getSampleModel(), dataset, srcRegion, destRegion, srcBands), false, null);
            } else {
                cm = imageType.getColorModel();
                bi = new BufferedImage(cm, (WritableRaster) readDatasetRaster(destSampleModel, dataset, srcRegion, destRegion, srcBands), false, null);
            }
        } else {
            // //
            // 
            // the destination image has been specified.
            // 
            // //
            // Rectangle destSize = (Rectangle) destRegion.clone();
            // destSize.setLocation(0, 0);
            Raster readRaster = readDatasetRaster(item.getSampleModel(), dataset, srcRegion, destRegion, srcBands);
            WritableRaster raster = bi.getRaster().createWritableChild(0, 0, bi.getWidth(), bi.getHeight(), 0, 0, null);
            // TODO: Work directly on a Databuffer avoiding setRect?
            raster.setRect(destRegion.x, destRegion.y, readRaster);
        // Raster readRaster = readDatasetRaster(item, srcRegion,
        // destRegion,
        // srcBands);
        // WritableRaster raster = bi.getRaster().createWritableChild(
        // destRegion.x, destRegion.y, destRegion.width,
        // destRegion.height, destRegion.x, destRegion.y, null);
        // //TODO: Work directly on a Databuffer avoiding setRect?
        // raster.setRect(readRaster);
        }
        return bi;
    } finally {
        if (warpedDataset != null) {
            GDALUtilities.closeDataSet(warpedDataset);
        }
    }
}
Also used : Dataset(org.gdal.gdal.Dataset) Raster(java.awt.image.Raster) WritableRaster(java.awt.image.WritableRaster) Rectangle(java.awt.Rectangle) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) ImageTypeSpecifier(javax.imageio.ImageTypeSpecifier) EnhancedImageReadParam(it.geosolutions.imageio.imageioimpl.EnhancedImageReadParam) EnhancedImageReadParam(it.geosolutions.imageio.imageioimpl.EnhancedImageReadParam) ImageReadParam(javax.imageio.ImageReadParam) SampleModel(java.awt.image.SampleModel) PixelInterleavedSampleModel(java.awt.image.PixelInterleavedSampleModel) BandedSampleModel(java.awt.image.BandedSampleModel) ColorModel(java.awt.image.ColorModel) WritableRaster(java.awt.image.WritableRaster) SpatialReference(org.gdal.osr.SpatialReference)

Example 3 with Dataset

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

the class GDALImageReaderSpi method canDecodeInput.

/**
 * Checks if the provided input can be decoded by the specific SPI. When
 * building a new plugin, remember to implement the
 * <code>getSupportedFormat</coded> abstract method.
 *
 * @return
 * 		<code>true</code> if the input can be successfully decoded.
 */
public boolean canDecodeInput(Object input) throws IOException {
    if (input == null)
        return false;
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine("Can Decode Input called with object " + input != null ? input.toString() : "null");
    File sourceFile = null;
    // convert input from String to File then try URL
    if (input instanceof String) {
        final File file = new File((String) input);
        if (!file.exists() || !file.canRead()) {
            // /check for URL
            input = new URL((String) input);
        } else
            input = file;
    }
    // if input source is an URL, open an InputStream
    if (input instanceof URL) {
        input = ImageIOUtilities.urlToFile((URL) input);
    }
    // convert input from File to FileInputStream
    if (input instanceof File)
        sourceFile = (File) input;
    // at this point it must be an instance of FileImageInputStreamExt to be able to proceed
    if (input instanceof FileImageInputStreamExt)
        sourceFile = ((FileImageInputStreamExt) input).getFile();
    if (sourceFile == null || !sourceFile.exists() || !sourceFile.canRead()) {
        return false;
    }
    boolean isInputDecodable = false;
    // Checking if this specific SPI can decode the provided input
    Dataset ds = null;
    try {
        ds = GDALUtilities.acquireDataSet(sourceFile.getAbsolutePath(), gdalconst.GA_ReadOnly);
        isInputDecodable = isDecodable(ds);
    } catch (Throwable e) {
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.log(Level.FINE, e.getLocalizedMessage(), e);
    } finally {
        if (ds != null)
            try {
                // Closing the dataset
                GDALUtilities.closeDataSet(ds);
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINEST))
                    LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
            }
    }
    return isInputDecodable;
}
Also used : Dataset(org.gdal.gdal.Dataset) FileImageInputStreamExt(it.geosolutions.imageio.stream.input.FileImageInputStreamExt) File(java.io.File) URL(java.net.URL)

Example 4 with Dataset

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

the class GDALUtilities method getGDALImageMetadata.

/**
 * Returns any metadata related to the specified image. The SUBDATASETS
 * domain is not returned since it is related to the whole stream instead of
 * a single image.
 *
 * @param dataSetName
 *                the name of the dataset for which we need to retrieve
 *                imageMetadata
 *
 * @return a <code>List</code> containing any metadata found.
 */
public static List<String> getGDALImageMetadata(String dataSetName) {
    final Dataset ds = acquireDataSet(dataSetName, gdalconst.GA_ReadOnly);
    final List<String> gdalImageMetadata;
    if (ds != null) {
        try {
            gdalImageMetadata = ds.GetMetadata_List("");
        } finally {
            // Closing the dataset
            closeDataSet(ds);
        }
    } else {
        gdalImageMetadata = null;
    }
    return gdalImageMetadata;
}
Also used : Dataset(org.gdal.gdal.Dataset)

Example 5 with Dataset

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

the class GDALImageWriter method createDatasetFromImage.

/**
 * Given an input <code>RenderedImage</code> builds a temporary
 * <code>Dataset</code> and fill it with data from the input image. Source
 * region settings are allowed in order to specify the desired portion of
 * input image which need to be used to populate the dataset.
 *
 * @param inputRenderedImage
 *                the input <code>RenderedImage</code> from which to get
 *                data
 * @param tempFile
 *                a fileName where to store the temporary dataset
 * @param sourceRegion
 *                a <code>Rectangle</code> specifying the desired portion
 *                of the input image which need to be used to populate the
 *                dataset.
 * @param nBands
 *                the number of the bands of the created dataset
 * @param dataType
 *                the dataType of the created dataset.
 * @param width
 *                the width of the created dataset
 * @param height
 *                the height of the created dataset
 * @param xSubsamplingFactor
 *                the X subsampling factor which need to be used when
 *                loading data from the input image
 * @param ySubsamplingFactor
 *                the Y subsampling factor which need to be used when
 *                loading data from the input image
 * @return a <code>Dataset</code> containing data coming from the input
 *         image
 */
private Dataset createDatasetFromImage(RenderedImage inputRenderedImage, final String tempFile, Rectangle sourceRegion, final int nBands, final int dataType, final int width, final int height, final int xSubsamplingFactor, final int ySubsamplingFactor) {
    // //
    // 
    // Attempting to build a "In memory" raster dataset
    // 
    // //
    Dataset tempDs = null;
    final int threshold = getMaxMemorySizeForGDALMemoryDataset();
    final int neededMemory = width * height * nBands * gdal.GetDataTypeSize(dataType) / 8;
    if (neededMemory <= threshold) {
        // TODO: the real Memory Raster Driver use should create a Memory
        // Dataset from data in memory by specifying the address of the
        // memory containing data.
        tempDs = getMemoryDriver().Create(tempFile, width, height, nBands, dataType, (String[]) null);
    }
    if (tempDs == null) {
        // //
        // 
        // Unable to allocate memory for In memory raster dataset
        // Using a GTiff driver to create a temp dataset
        // 
        // //
        final Driver driver = gdal.GetDriverByName("GTiff");
        tempDs = driver.Create(tempFile, width, height, nBands, dataType, (String[]) null);
    }
    // //
    return writeData(tempDs, inputRenderedImage, sourceRegion, nBands, dataType, xSubsamplingFactor, ySubsamplingFactor);
}
Also used : Dataset(org.gdal.gdal.Dataset) Driver(org.gdal.gdal.Driver)

Aggregations

Dataset (org.gdal.gdal.Dataset)11 File (java.io.File)3 FileImageInputStreamExt (it.geosolutions.imageio.stream.input.FileImageInputStreamExt)2 Dimension (java.awt.Dimension)2 Rectangle (java.awt.Rectangle)2 BufferedImage (java.awt.image.BufferedImage)2 IOException (java.io.IOException)2 URL (java.net.URL)2 Vector (java.util.Vector)2 Driver (org.gdal.gdal.Driver)2 BoundingBox (com.revolsys.geometry.model.BoundingBox)1 PathResource (com.revolsys.spring.resource.PathResource)1 Resource (com.revolsys.spring.resource.Resource)1 GCP (it.geosolutions.imageio.core.GCP)1 DriverCreateCapabilities (it.geosolutions.imageio.gdalframework.GDALUtilities.DriverCreateCapabilities)1 EnhancedImageReadParam (it.geosolutions.imageio.imageioimpl.EnhancedImageReadParam)1 URIImageInputStream (it.geosolutions.imageio.stream.input.URIImageInputStream)1 BandedSampleModel (java.awt.image.BandedSampleModel)1 ColorModel (java.awt.image.ColorModel)1 PixelInterleavedSampleModel (java.awt.image.PixelInterleavedSampleModel)1