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);
}
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;
}
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());
}
}
Aggregations