Search in sources :

Example 1 with Driver

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

the class GDALImageReaderSpi method isDecodable.

/**
 * Checks if the provided Dataset was opened by a Driver supporting the same
 * formats which are supported by the specific ImageReaderSpi.
 *
 * There is a trivial example: Suppose we are implementing a plugin for HDF4
 * format and suppose we are testing the <code>canDecodeInput</code> with
 * a NITF file as input. GDAL will successfully open the NITF file. However,
 * it will use the NITF driver instead of the HDF4 driver. Since NITF is not
 * supported by the HDF4ImageReaderSpi, this method will return return
 * <code>false</code>.
 *
 * @param dataset
 *                The input dataset
 *
 * @return <code>true</code> if the format is supported.
 *         <code>false</code> otherwise.
 */
protected boolean isDecodable(Dataset dataset) {
    if (dataset != null) {
        final Driver driver = dataset.GetDriver();
        // retrieving the format of the provided input.
        // We use the "Description" of the driver which has opened the
        // input.
        final String sDriver = driver.getShortName();
        // checking if this format is supported by the specific SPI */
        return getSupportedFormats().contains(sDriver);
    }
    return false;
}
Also used : Driver(org.gdal.gdal.Driver)

Example 2 with Driver

use of org.gdal.gdal.Driver 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)

Example 3 with Driver

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

the class GDALImageWriter method write.

/**
 * Write the input image to the output.
 * <p>
 * The output must have been set beforehand using the <code>setOutput</code>
 * method.
 *
 * <p>
 * An <code>ImageWriteParam</code> may optionally be supplied to control
 * the writing process. If <code>param</code> is <code>null</code>, a
 * default write param will be used.
 *
 * <p>
 * If the supplied <code>ImageWriteParam</code> contains optional setting
 * values not supported by this writer (<i>e.g.</i> progressive encoding
 * or any format-specific settings), they will be ignored.
 *
 * @param streamMetadata
 *                an <code>IIOMetadata</code> object representing stream
 *                metadata, or <code>null</code> to use default values.
 * @param image
 *                an <code>IIOImage</code> object containing an image, and
 *                metadata to be written. Note that metadata is actually
 *                supposed to be an instance of
 *                {@link GDALCommonIIOImageMetadata}.
 *                {@link GDALWritableCommonIIOImageMetadata} may be used to
 *                set properties from other type of ImageMetadata to a
 *                format which is understood by this writer.
 * @param param
 *                an <code>ImageWriteParam</code>, or <code>null</code>
 *                to use a default <code>ImageWriteParam</code>.
 *
 * @exception IllegalStateException
 *                    if the output has not been set.
 * @exception IllegalArgumentException
 *                    if <code>image</code> is <code>null</code>.
 * @exception IOException
 *                    if an error occurs during writing.
 */
public void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param) throws IOException {
    if (outputFile == null) {
        throw new IllegalStateException("the output is null!");
    }
    if (param == null)
        param = getDefaultWriteParam();
    // /////////////////////////////////////////////////////////////////////
    // 
    // Initial check on the capabilities of this writer as well as the
    // provided parameters.
    // 
    // /////////////////////////////////////////////////////////////////////
    final String driverName = (String) ((GDALImageWriterSpi) this.originatingProvider).getSupportedFormats().get(0);
    final DriverCreateCapabilities writingCapabilities = GDALUtilities.formatWritingCapabilities(driverName);
    if (writingCapabilities == GDALUtilities.DriverCreateCapabilities.READ_ONLY)
        throw new IllegalStateException("This writer seems to not support either create or create copy");
    if (image == null)
        throw new IllegalArgumentException("The provided input image is invalid.");
    // //
    // 
    // Getting the source image and its main properties
    // 
    // //
    final PlanarImage inputRenderedImage = PlanarImage.wrapRenderedImage(image.getRenderedImage());
    final int sourceWidth = inputRenderedImage.getWidth();
    final int sourceHeight = inputRenderedImage.getHeight();
    final int sourceMinX = inputRenderedImage.getMinX();
    final int sourceMinY = inputRenderedImage.getMinY();
    final int dataType = GDALUtilities.retrieveGDALDataBufferType(inputRenderedImage.getSampleModel().getDataType());
    final int nBands = inputRenderedImage.getNumBands();
    // //
    // 
    // Setting regions and sizes and retrieving parameters
    // 
    // //
    final int xSubsamplingFactor = param.getSourceXSubsampling();
    final int ySubsamplingFactor = param.getSourceYSubsampling();
    final Vector<String> myOptions = (Vector<String>) ((GDALImageWriteParam) param).getCreateOptionsHandler().getCreateOptions();
    Rectangle imageBounds = new Rectangle(sourceMinX, sourceMinY, sourceWidth, sourceHeight);
    Dimension destSize = new Dimension();
    computeRegions(imageBounds, destSize, param);
    // Destination sizes, needed for Dataset Creation
    final int destinationWidth = destSize.width;
    final int destinationHeight = destSize.height;
    // getting metadata before deciding if Create or CreateCopy will be used
    final IIOMetadata metadata = image.getMetadata();
    GDALCommonIIOImageMetadata imageMetadata = null;
    if (metadata != null) {
        if (metadata instanceof GDALCommonIIOImageMetadata) {
            imageMetadata = (GDALCommonIIOImageMetadata) metadata;
        } else {
        // TODO: build a metadata conversion to obtain an understandable
        // metadata object. Standard plugin-neutral format does not
        // contain really useful fields to be converted.
        // imageMetadata = new GDALWritableCommonIIOImageMetadata();
        // convertMetadata(IMAGE_METADATA_NAME, metadata,
        // imageMetadata);
        }
    }
    // /////////////////////////////////////////////////////////////////////
    // 
    // Some GDAL formats driver support both "Create" and "CreateCopy"
    // methods. Some others simply support "CreateCopy" method which only
    // allows to create a new File from an existing Dataset.
    // 
    // /////////////////////////////////////////////////////////////////////
    Dataset writeDataset = null;
    Driver driver = null;
    try {
        if (writingCapabilities == GDALUtilities.DriverCreateCapabilities.CREATE) {
            // /////////////////////////////////////////////////////////////////
            // 
            // Create is supported
            // -------------------
            // 
            // /////////////////////////////////////////////////////////////////
            // Retrieving the file name.
            final String fileName = outputFile.getAbsolutePath();
            // //
            // 
            // Dataset creation
            // 
            // //
            driver = gdal.GetDriverByName(driverName);
            writeDataset = driver.Create(fileName, destinationWidth, destinationHeight, nBands, dataType, myOptions);
            // //
            // 
            // Data Writing
            // 
            // //
            writeDataset = writeData(writeDataset, inputRenderedImage, imageBounds, nBands, dataType, xSubsamplingFactor, ySubsamplingFactor);
            // //
            if (imageMetadata != null) {
                setMetadata(writeDataset, imageMetadata);
            }
        } else {
            // ////////////////////////////////////////////////////////////////
            // 
            // Only CreateCopy is supported
            // ----------------------------------------------------------------
            // 
            // First of all, it is worth to point out that CreateCopy method
            // allows to create a File from an existing Dataset.
            // ////////////////////////////////////////////////////////////////
            driver = gdal.GetDriverByName(driverName);
            // //
            // 
            // Temporary Dataset creation from the originating image
            // 
            // //
            final File tempFile = File.createTempFile("datasetTemp", ".ds", null);
            Dataset tempDataset = null;
            try {
                tempDataset = createDatasetFromImage(inputRenderedImage, tempFile.getAbsolutePath(), imageBounds, nBands, dataType, destinationWidth, destinationHeight, xSubsamplingFactor, ySubsamplingFactor);
                tempDataset.FlushCache();
                // //
                if (imageMetadata != null) {
                    setMetadata(tempDataset, imageMetadata);
                }
                // //
                // 
                // Copy back the temporary dataset to the requested dataset
                // 
                // //
                writeDataset = driver.CreateCopy(outputFile.getPath(), tempDataset, 0, myOptions);
            } finally {
                if (tempDataset != null) {
                    try {
                        // Closing the dataset
                        GDALUtilities.closeDataSet(tempDataset);
                    } catch (Throwable e) {
                        if (LOGGER.isLoggable(Level.FINEST))
                            LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
                    }
                }
            }
            tempFile.delete();
        }
        // //
        // 
        // Flushing and closing dataset
        // 
        // //
        writeDataset.FlushCache();
    } finally {
        if (writeDataset != null) {
            try {
                // Closing the dataset
                GDALUtilities.closeDataSet(writeDataset);
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINEST))
                    LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
            }
        }
        if (driver != null) {
            try {
                // Closing the driver
                driver.delete();
            } catch (Throwable e) {
                if (LOGGER.isLoggable(Level.FINEST))
                    LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
            }
        }
    }
}
Also used : Dataset(org.gdal.gdal.Dataset) Rectangle(java.awt.Rectangle) Driver(org.gdal.gdal.Driver) Dimension(java.awt.Dimension) IIOMetadata(javax.imageio.metadata.IIOMetadata) DriverCreateCapabilities(it.geosolutions.imageio.gdalframework.GDALUtilities.DriverCreateCapabilities) Vector(java.util.Vector) File(java.io.File) PlanarImage(javax.media.jai.PlanarImage)

Example 4 with Driver

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

the class GDALUtilities method formatWritingCapabilities.

/**
 * Tells us about the capabilities for a GDAL driver.
 *
 * @param driverName
 *                name of the {@link Driver} we want to get info about.
 * @return {@link GDALUtilities.DriverCreateCapabilities#CREATE} in case the
 *         driver supports creation of dataset,
 *         {@link GDALUtilities.DriverCreateCapabilities#CREATE_COPY} in
 *         case the driver supports only create copy and eventually
 *         {@link GDALUtilities.DriverCreateCapabilities#READ_ONLY} for
 *         read-only drivers.
 * @throws IllegalArgumentException
 *                 in case the specified driver name is <code>null</code>
 *                 or a Driver for the specified name is unavailable.
 */
public static DriverCreateCapabilities formatWritingCapabilities(final String driverName) {
    if (driverName == null)
        throw new IllegalArgumentException("The provided driver name is null");
    loadGDAL();
    synchronized (driversWritingCapabilities) {
        if (driversWritingCapabilities.containsKey(driverName))
            return (driversWritingCapabilities.get(driverName));
        final Driver driver = gdal.GetDriverByName(driverName);
        try {
            if (driver == null)
                throw new IllegalArgumentException("A Driver with the specified name is unavailable. " + "Check the specified name or be sure this " + "Driver is supported");
            // parse metadata
            final Map metadata = driver.GetMetadata_Dict("");
            final String create = (String) metadata.get("DCAP_CREATE");
            final String createCopy = (String) metadata.get("DCAP_CREATECOPY");
            final boolean createSupported = create != null && create.equalsIgnoreCase("yes");
            final boolean createCopySupported = createCopy != null && createCopy.equalsIgnoreCase("yes");
            DriverCreateCapabilities retVal;
            if (createSupported) {
                driversWritingCapabilities.put(driverName, GDALUtilities.DriverCreateCapabilities.CREATE);
                return GDALUtilities.DriverCreateCapabilities.CREATE;
            } else if (createCopySupported) {
                driversWritingCapabilities.put(driverName, GDALUtilities.DriverCreateCapabilities.CREATE_COPY);
                return GDALUtilities.DriverCreateCapabilities.CREATE_COPY;
            } else {
                driversWritingCapabilities.put(driverName, GDALUtilities.DriverCreateCapabilities.READ_ONLY);
                return GDALUtilities.DriverCreateCapabilities.READ_ONLY;
            }
        } finally {
            if (driver != null) {
                try {
                    // Closing the driver
                    driver.delete();
                } catch (Throwable e) {
                    if (LOGGER.isLoggable(Level.FINEST))
                        LOGGER.log(Level.FINEST, e.getLocalizedMessage(), e);
                }
            }
        }
    }
}
Also used : Driver(org.gdal.gdal.Driver) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

Driver (org.gdal.gdal.Driver)4 Dataset (org.gdal.gdal.Dataset)2 DriverCreateCapabilities (it.geosolutions.imageio.gdalframework.GDALUtilities.DriverCreateCapabilities)1 Dimension (java.awt.Dimension)1 Rectangle (java.awt.Rectangle)1 File (java.io.File)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 Vector (java.util.Vector)1 IIOMetadata (javax.imageio.metadata.IIOMetadata)1 PlanarImage (javax.media.jai.PlanarImage)1