Search in sources :

Example 6 with FileImageInputStreamExt

use of it.geosolutions.imageio.stream.input.FileImageInputStreamExt in project imageio-ext by geosolutions-it.

the class JP2KKakaduImageReader method setInput.

public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
    // //
    // 
    // Reset the reader prior to do anything with it
    // 
    // //
    reset();
    // //
    if (input == null)
        throw new NullPointerException("The provided input is null!");
    // Checking if the provided input is a File
    if (input instanceof File) {
        inputFile = (File) input;
    // Checking if the provided input is a FileImageInputStreamExt
    } else if (input instanceof FileImageInputStreamExt) {
        inputFile = ((FileImageInputStreamExt) input).getFile();
    // Checking if the provided input is a URL
    } else if (input instanceof URL) {
        final URL tempURL = (URL) input;
        if (tempURL.getProtocol().equalsIgnoreCase("file")) {
            inputFile = Utilities.urlToFile(tempURL);
        }
    } else if (input instanceof ImageInputStream) {
        try {
            inputFile = File.createTempFile("buffer", ".j2c");
            FileOutputStream fos = new FileOutputStream(inputFile);
            final byte[] buff = new byte[TEMP_BUFFER_SIZE];
            int bytesRead = 0;
            while ((bytesRead = ((ImageInputStream) input).read(buff)) != -1) fos.write(buff, 0, bytesRead);
            fos.close();
            input = inputFile;
            deleteInputFile = true;
        } catch (IOException ioe) {
            throw new RuntimeException("Unable to create a temp file", ioe);
        }
    }
    if (this.inputFile == null)
        throw new IllegalArgumentException("Invalid source provided.");
    fileName = inputFile.getAbsolutePath();
    // //
    // 
    // Open it up
    // 
    // //
    // Must be disposed last
    Kdu_simple_file_source rawSource = null;
    // Dispose
    final Jp2_family_src familySource = new Jp2_family_src();
    // last
    // Dispose in the
    final Jpx_source wrappedSource = new Jpx_source();
    // middle
    Kdu_codestream codestream = new Kdu_codestream();
    try {
        // Open input file as raw codestream or a JP2/JPX file
        familySource.Open(fileName);
        final int success = wrappedSource.Open(familySource, true);
        if (success < 0) {
            // //
            // 
            // Must open as raw file
            // 
            // //
            familySource.Close();
            wrappedSource.Close();
            rawSource = new Kdu_simple_file_source(fileName);
            if (rawSource != null) {
                if (fileName != null) {
                    FileInputStream fis = new FileInputStream(new File(fileName));
                    byte[] jp2SocMarker = new byte[2];
                    fis.read(jp2SocMarker);
                    if (jp2SocMarker[0] != (byte) 0xFF || jp2SocMarker[1] != (byte) 0x4F)
                        throw new IllegalArgumentException("Not a JP2K source.");
                    fis.close();
                }
                isRawSource = true;
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine("Detected raw source");
                numImages = 1;
            }
        } else {
            // we have a valid jp2/jpx file
            isRawSource = false;
            // //
            // 
            // get the number of codestreams in this jpeg2000 file
            // 
            // //
            final int[] count = new int[1];
            if (wrappedSource.Count_codestreams(count))
                numImages = count[0];
            else
                numImages = 0;
        }
        if (!isRawSource)
            fileWalker = new JP2KFileWalker(this.fileName);
        for (int cs = 0; cs < numImages; cs++) {
            if (isRawSource) {
                codestream.Create(rawSource);
            } else {
                final Jpx_codestream_source stream = wrappedSource.Access_codestream(cs);
                final Jpx_input_box inputbox = stream.Open_stream();
                codestream.Create(inputbox);
            }
            final JP2KCodestreamProperties codestreamP = new JP2KCodestreamProperties();
            // //
            // 
            // Initializing size-related properties (Image dims, Tiles)
            // 
            // //
            final Kdu_dims imageDims = new Kdu_dims();
            codestream.Access_siz().Finalize_all();
            codestream.Get_dims(-1, imageDims, false);
            final Kdu_dims tileSize = new Kdu_dims();
            codestream.Get_tile_dims(new Kdu_coords(0, 0), -1, tileSize);
            int tileWidth = tileSize.Access_size().Get_x();
            int tileHeight = tileSize.Access_size().Get_y();
            // maximum integer
            if ((float) tileWidth * tileHeight >= Integer.MAX_VALUE) {
                // TODO: Customize these settings
                tileHeight = 1024;
                tileWidth = 1024;
            }
            codestreamP.setTileWidth(tileWidth);
            codestreamP.setTileHeight(tileHeight);
            codestreamP.setWidth(imageDims.Access_size().Get_x());
            codestreamP.setHeight(imageDims.Access_size().Get_y());
            final int nComponents = codestream.Get_num_components();
            int maxBitDepth = -1;
            int[] componentIndexes = new int[nComponents];
            int[] bitsPerComponent = new int[nComponents];
            boolean isSigned = false;
            for (int i = 0; i < nComponents; i++) {
                // TODO: FIX THIS
                bitsPerComponent[i] = codestream.Get_bit_depth(i);
                if (maxBitDepth < bitsPerComponent[i]) {
                    maxBitDepth = bitsPerComponent[i];
                }
                isSigned |= codestream.Get_signed(i);
                componentIndexes[i] = i;
            }
            codestreamP.setNumComponents(nComponents);
            codestreamP.setBitsPerComponent(bitsPerComponent);
            codestreamP.setComponentIndexes(componentIndexes);
            codestreamP.setMaxBitDepth(maxBitDepth);
            codestreamP.setSigned(isSigned);
            // Initializing Resolution levels and Quality Layers
            final int sourceDWTLevels = codestream.Get_min_dwt_levels();
            codestreamP.setSourceDWTLevels(sourceDWTLevels);
            codestreamP.setMaxSupportedSubSamplingFactor(1 << sourceDWTLevels);
            Kdu_coords tileCoords = new Kdu_coords();
            tileCoords.Set_x(0);
            tileCoords.Set_y(0);
            codestream.Open_tile(tileCoords);
            codestreamP.setMaxAvailableQualityLayers(codestream.Get_max_tile_layers());
            initializeSampleModelAndColorModel(codestreamP);
            codestream.Destroy();
            multipleCodestreams.add(codestreamP);
            if (isRawSource)
                break;
        }
    } catch (KduException e) {
        throw new RuntimeException("Error caused by a Kakadu exception during creation of key objects!", e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException("Exception occurred during kakadu reader initialization", e);
    } catch (IOException e) {
        throw new RuntimeException("Exception occurred during kakadu reader initialization", e);
    } finally {
        if (!isRawSource && wrappedSource != null) {
            try {
                if (wrappedSource.Exists())
                    wrappedSource.Close();
            } catch (Throwable e) {
            // yeah I am eating this
            }
            try {
                wrappedSource.Native_destroy();
            } catch (Throwable e) {
            // yeah I am eating this
            }
            if (familySource != null) {
                try {
                    if (familySource.Exists())
                        familySource.Close();
                } catch (Throwable e) {
                // yeah I am eating this
                }
                try {
                    familySource.Native_destroy();
                } catch (Throwable e) {
                // yeah I am eating this
                }
            }
        } else if (isRawSource && rawSource != null) {
            try {
                if (wrappedSource.Exists())
                    wrappedSource.Close();
            } catch (Throwable e) {
            // yeah I am eating this
            }
        }
    }
    // //
    // 
    // Setting input for superclass
    // 
    // //
    super.setInput(input, seekForwardOnly, ignoreMetadata);
}
Also used : FileNotFoundException(java.io.FileNotFoundException) URL(java.net.URL) Jpx_source(kdu_jni.Jpx_source) Kdu_dims(kdu_jni.Kdu_dims) FileImageInputStreamExt(it.geosolutions.imageio.stream.input.FileImageInputStreamExt) Kdu_codestream(kdu_jni.Kdu_codestream) KduException(kdu_jni.KduException) Kdu_simple_file_source(kdu_jni.Kdu_simple_file_source) Jpx_codestream_source(kdu_jni.Jpx_codestream_source) ImageInputStream(javax.imageio.stream.ImageInputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) Kdu_coords(kdu_jni.Kdu_coords) Jpx_input_box(kdu_jni.Jpx_input_box) Jp2_family_src(kdu_jni.Jp2_family_src) File(java.io.File)

Example 7 with FileImageInputStreamExt

use of it.geosolutions.imageio.stream.input.FileImageInputStreamExt in project imageio-ext by geosolutions-it.

the class JP2KKakaduImageReaderSpi method canDecodeInput.

/**
 * This method checks if the provided input can be decoded from this SPI
 */
public boolean canDecodeInput(Object input) throws IOException {
    boolean isDecodable = true;
    File source = null;
    // Retrieving the File source
    if (input instanceof File) {
        source = (File) input;
    } else if (input instanceof FileImageInputStreamExt) {
        source = ((FileImageInputStreamExt) input).getFile();
    } else if (input instanceof URL) {
        final URL tempURL = (URL) input;
        if (tempURL.getProtocol().equalsIgnoreCase("file")) {
            source = Utilities.urlToFile(tempURL);
        }
    } else
        return false;
    Jp2_family_src familySource = new Jp2_family_src();
    Jpx_source wrappedSource = new Jpx_source();
    Kdu_simple_file_source rawSource = null;
    try {
        String fileName = source.getAbsolutePath();
        familySource.Open(fileName);
        int success = wrappedSource.Open(familySource, true);
        // specifications
        if (success < 0) {
            // Must open as a raw file
            familySource.Close();
            wrappedSource.Close();
            rawSource = new Kdu_simple_file_source(fileName);
            if (rawSource != null) {
                if (fileName != null) {
                    FileInputStream fis = new FileInputStream(new File(fileName));
                    byte[] jp2SocMarker = new byte[2];
                    fis.read(jp2SocMarker);
                    if (jp2SocMarker[0] == (byte) 0xFF && jp2SocMarker[1] == (byte) 0x4F)
                        isDecodable = true;
                    else
                        isDecodable = false;
                    fis.close();
                }
            } else
                isDecodable = false;
        }
    } catch (KduException e) {
        throw new RuntimeException("Error caused by a Kakadu exception during creation of key objects! ", e);
    }
    // Dispose
    wrappedSource.Native_destroy();
    familySource.Native_destroy();
    if (rawSource != null)
        rawSource.Native_destroy();
    return isDecodable;
}
Also used : KduException(kdu_jni.KduException) Kdu_simple_file_source(kdu_jni.Kdu_simple_file_source) URL(java.net.URL) FileInputStream(java.io.FileInputStream) Jpx_source(kdu_jni.Jpx_source) FileImageInputStreamExt(it.geosolutions.imageio.stream.input.FileImageInputStreamExt) Jp2_family_src(kdu_jni.Jp2_family_src) File(java.io.File)

Example 8 with FileImageInputStreamExt

use of it.geosolutions.imageio.stream.input.FileImageInputStreamExt in project imageio-ext by geosolutions-it.

the class GDALImageReader method setInput.

/**
 * Sets the input for the specialized reader.
 *
 * @throws IllegalArgumentException
 *                 if the provided input is <code>null</code>
 */
public void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata) {
    if (LOGGER.isLoggable(Level.FINE))
        LOGGER.fine("Setting Input");
    // check input
    if (input == null)
        throw new IllegalArgumentException("The provided input is null!");
    // is gdal available
    if (!GDALUtilities.isGDALAvailable())
        throw new IllegalStateException("GDAL native libraries are not available.");
    // to clear any value-object which was related to the previous input.
    if (this.imageInputStream != null) {
        reset();
        imageInputStream = null;
    }
    // //
    if (input instanceof File) {
        datasetSource = (File) input;
        try {
            imageInputStream = ImageIO.createImageInputStream(input);
        } catch (IOException e) {
            throw new RuntimeException("Failed to create a valid input stream ", e);
        }
    } else // //
    if (input instanceof FileImageInputStreamExt) {
        datasetSource = ((FileImageInputStreamExt) input).getFile();
        imageInputStream = (ImageInputStream) input;
    } else // //
    if (input instanceof URL) {
        final URL tempURL = (URL) input;
        if (tempURL.getProtocol().equalsIgnoreCase("file")) {
            try {
                datasetSource = ImageIOUtilities.urlToFile(tempURL);
                imageInputStream = ImageIO.createImageInputStream(input);
            } catch (IOException e) {
                throw new RuntimeException("Failed to create a valid input stream ", e);
            }
        }
    } else if (input instanceof URIImageInputStream) {
        imageInputStream = (URIImageInputStream) input;
        datasetSource = null;
        uriSource = ((URIImageInputStream) input).getUri();
    }
    // 
    // Checking if this input is of a supported format.
    // Now, I have an ImageInputStream and I can try to see if the input's
    // format is supported by the specialized reader
    // 
    boolean isInputDecodable = false;
    String mainDatasetName = null;
    Dataset mainDataSet = null;
    if (imageInputStream != null) {
        if (datasetSource != null) {
            mainDatasetName = datasetSource.getAbsolutePath();
            mainDataSet = GDALUtilities.acquireDataSet(datasetSource.getAbsolutePath(), gdalconstConstants.GA_ReadOnly);
        } else if (uriSource != null) {
            final String urisource = uriSource.toString();
            mainDatasetName = urisource;
            mainDataSet = GDALUtilities.acquireDataSet(urisource, gdalconstConstants.GA_ReadOnly);
        }
        if (mainDataSet != null) {
            isInputDecodable = ((GDALImageReaderSpi) this.getOriginatingProvider()).isDecodable(mainDataSet);
        } else
            isInputDecodable = false;
    }
    if (isInputDecodable) {
        // cache dataset
        datasetsMap.put(mainDatasetName, mainDataSet);
        // input is decodable
        super.setInput(imageInputStream, seekForwardOnly, ignoreMetadata);
        // Listing available subdatasets
        final List<String> subdatasets = mainDataSet.GetMetadata_List(GDALUtilities.GDALMetadataDomain.SUBDATASETS);
        // setting the number of subdatasets
        // It is worth to remind that the subdatasets vector
        // contains both Subdataset's Name and Subdataset's Description
        // Thus we need to divide its size by two.
        nSubdatasets = subdatasets.size() / 2;
        // Thus, theDataset is simply the main dataset.
        if (nSubdatasets == 0) {
            nSubdatasets = 1;
            datasetNames = new String[1];
            datasetNames[0] = mainDatasetName;
            datasetMetadataMap.put(datasetNames[0], this.createDatasetMetadata(mainDatasetName));
        } else {
            datasetNames = new String[nSubdatasets + 1];
            for (int i = 0; i < nSubdatasets; i++) {
                final String subdatasetName = (subdatasets.get(i * 2)).toString();
                final int nameStartAt = subdatasetName.lastIndexOf("_NAME=") + 6;
                datasetNames[i] = subdatasetName.substring(nameStartAt);
            }
            datasetNames[nSubdatasets] = mainDatasetName;
            datasetMetadataMap.put(datasetNames[nSubdatasets], createDatasetMetadata(mainDataSet, datasetNames[nSubdatasets]));
        }
        // clean list
        subdatasets.clear();
    } else {
        StringBuilder sb = new StringBuilder();
        if (imageInputStream == null) {
            sb.append("Unable to create a valid ImageInputStream for the provided input:");
            sb.append(GDALUtilities.NEWLINE);
            sb.append(input.toString());
        } else
            sb.append("The Provided input is not supported by this reader");
        throw new RuntimeException(sb.toString());
    }
}
Also used : Dataset(org.gdal.gdal.Dataset) ImageInputStream(javax.imageio.stream.ImageInputStream) URIImageInputStream(it.geosolutions.imageio.stream.input.URIImageInputStream) IOException(java.io.IOException) URL(java.net.URL) FileImageInputStreamExt(it.geosolutions.imageio.stream.input.FileImageInputStreamExt) File(java.io.File) URIImageInputStream(it.geosolutions.imageio.stream.input.URIImageInputStream)

Aggregations

FileImageInputStreamExt (it.geosolutions.imageio.stream.input.FileImageInputStreamExt)8 File (java.io.File)8 IOException (java.io.IOException)5 FileImageInputStreamExtImpl (it.geosolutions.imageio.stream.input.FileImageInputStreamExtImpl)4 URL (java.net.URL)4 Test (org.junit.Test)3 TIFFImageReader (it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReader)2 TIFFImageReaderSpi (it.geosolutions.imageioimpl.plugins.tiff.TIFFImageReaderSpi)2 MetadataNode (it.geosolutions.imageioimpl.plugins.tiff.TIFFStreamMetadata.MetadataNode)2 Rectangle (java.awt.Rectangle)2 BufferedImage (java.awt.image.BufferedImage)2 FileInputStream (java.io.FileInputStream)2 ImageReadParam (javax.imageio.ImageReadParam)2 IIOMetadata (javax.imageio.metadata.IIOMetadata)2 IIOMetadataNode (javax.imageio.metadata.IIOMetadataNode)2 ImageInputStream (javax.imageio.stream.ImageInputStream)2 Jp2_family_src (kdu_jni.Jp2_family_src)2 Jpx_source (kdu_jni.Jpx_source)2 KduException (kdu_jni.KduException)2 Kdu_simple_file_source (kdu_jni.Kdu_simple_file_source)2