|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||
ObjectImageReader
SpatialImageReader
public abstract class SpatialImageReader
Base class for readers of spatial (usually geographic) data. This class extends the standard
ImageReader class in order to improve the support of file formats having the following
characteristics:
IndexColorModel does not support negative values.
New API
This class provides the following API, which are new compared to the standard ImageReader
class:
getStreamMetadata() and getImageMetadata(int) is
restricted to SpatialMetadata.getDefaultReadParam() is restricted to
SpatialImageReadParam.getNumBands(int), returns the number of bands in the specified
image. Note that the bands may not contain color components in scientific dataset.getDimension(int), returns the dimension of the given image.
In some formats like NetCDF, an "image" is actually a dataset which may have more than
2 dimensions.
Services for implementors
This class provides the following conveniences for implementors. Note that the default behavior
described below assumes the simplest file format: one image made of one band of floating point
values using a grayscale color palette scaled to fit the range of sample values. This behavior
can be changed by overriding the methods listed below.
Provides default getNumImages(boolean) and getNumBands(int)
implementations, which return 1. This default behavior matches simple image formats
like RAW or
ASCII files.
Those methods need to be overridden for more complex image formats.
Provides checkImageIndex(int) and checkBandIndex(int,int) convenience
methods. Those methods are invoked by most implementation of public methods. They perform
their checks based on the informations provided by the above-cited getNumImages(boolean)
and getNumBands(int) methods.
Provides default implementations of getImageTypes(int) and
getRawImageType(int) methods, which assume that only one image type is offered.
The offered type is described by a default image type
specifier created from the informations provided by getRawDataType(int) and
getImageMetadata(int).
Provides getStreamMetadata() and getImageMetadata(int) default
implementations, which return null as authorized by the specification.
See the getDestination(int, ImageReadParam, int, int, SampleConverter[]) method for an
example of code using some of the services provided by this class.
SpatialImageWriter
| coverage/geotk-coverageio (download) | View source code for this class |
| Nested Class Summary | |
|---|---|
protected static class |
SpatialImageReader.Spi
Service provider interfaces (SPI) for SpatialImageReaders. |
| Field Summary |
|---|
| Fields inherited from class ImageReader |
|---|
availableLocales, ignoreMetadata, input, locale, minIndex, originatingProvider, progressListeners, seekForwardOnly, updateListeners, warningListeners, warningLocales |
| Fields inherited from interface WarningProducer |
|---|
LOGGER |
| Constructor Summary | |
|---|---|
protected |
SpatialImageReader(SpatialImageReader.Spi provider)
Constructs a new image reader. |
| Method Summary | |
|---|---|
protected void |
checkBandIndex(int imageIndex,
int bandIndex)
Ensures that the specified band index is inside the expected range. |
protected void |
checkImageIndex(int imageIndex)
Ensures that the specified image index is inside the expected range. |
protected void |
close()
Invoked when a new input is set or when the reader is disposed. |
protected boolean |
collapseNoDataValues(boolean isZeroValid,
double[] nodataValues,
int unusedSpace)
Returns true if the no-data values should be collapsed to 0 in order to save memory. |
protected SpatialMetadata |
createMetadata(int imageIndex)
Creates a new stream or image metadata. |
void |
dispose()
Allows any resources held by this reader to be released. |
SpatialImageReadParam |
getDefaultReadParam()
Returns a default parameter object appropriate for this format. |
protected BufferedImage |
getDestination(int imageIndex,
ImageReadParam parameters,
int width,
int height,
SampleConverter[] converters)
Returns the buffered image to which decoded pixel data should be written. |
int |
getDimension(int imageIndex)
Returns the number of dimension of the image at the given index. |
GridEnvelope |
getGridEnvelope(int imageIndex)
Returns the grid envelope of the image at the given index. |
SpatialMetadata |
getImageMetadata(int imageIndex)
Returns metadata associated with the given image. |
protected ImageTypeSpecifier |
getImageType(int imageIndex,
ImageReadParam parameters,
SampleConverter[] converters)
Returns an image type specifier indicating the SampleModel and ColorModel
to use for reading the image. |
Iterator<ImageTypeSpecifier> |
getImageTypes(int imageIndex)
Returns a collection of ImageTypeSpecifier containing possible image types to which
the given image may be decoded. |
int |
getNumBands(int imageIndex)
Returns the number of bands available for the specified image. |
int |
getNumImages(boolean allowSearch)
Returns the number of images available from the current input source. |
protected int |
getRawDataType(int imageIndex)
Returns the data type which most closely represents the "raw" internal data of the image. |
ImageTypeSpecifier |
getRawImageType(int imageIndex)
Returns an image type specifier indicating the SampleModel and ColorModel
which most closely represents the "raw" internal format of the image. |
SpatialMetadata |
getStreamMetadata()
Returns metadata associated with the input source as a whole. |
boolean |
hasColors(int imageIndex)
Returns true if the image at the given index has a color palette. |
void |
setInput(Object input,
boolean seekForwardOnly,
boolean ignoreMetadata)
Sets the input source to use. |
boolean |
warningOccurred(LogRecord record)
Invoked when a warning occurred. |
| Methods inherited from class Object |
|---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Methods inherited from interface Localized |
|---|
getLocale |
| Constructor Detail |
|---|
protected SpatialImageReader(SpatialImageReader.Spi provider)
provider - The ImageReaderSpi that is constructing this object, or null.| Method Detail |
|---|
public void setInput(Object input,
boolean seekForwardOnly,
boolean ignoreMetadata)
close()
before to set the new input.
setInput in class ImageReaderinput - The input object to use for future decoding.seekForwardOnly - If true, images and metadata may only be read
in ascending order from this input source.ignoreMetadata - If true, metadata may be ignored during reads.
protected void checkImageIndex(int imageIndex)
throws IOException,
IndexOutOfBoundsException
minIndex inclusive (initially 0)
to getNumImages(false) exclusive.
If getNumImages(false) returned -1, then this method does not
check the upper bound.
imageIndex - Index to check for validity.
IndexOutOfBoundsException - if the specified index is outside the expected range.
IOException - If the operation failed because of an I/O error.
protected void checkBandIndex(int imageIndex,
int bandIndex)
throws IOException,
IndexOutOfBoundsException
getNumBands(imageIndex)
exclusive.
imageIndex - The image index.bandIndex - Index to check for validity.
IndexOutOfBoundsException - if the specified index is outside the expected range.
IOException - If the operation failed because of an I/O error.
public int getNumImages(boolean allowSearch)
throws IllegalStateException,
IOException
getNumImages in class ImageReaderallowSearch - If true, the number of images will be returned
even if a search is required.
allowSearch
is false and a search would be required.
IllegalStateException - if the input source has not been set.
IOException - if an error occurs reading the information from the input source.
public int getNumBands(int imageIndex)
throws IOException
imageIndex - The image index.
IOException - if an error occurs reading the information from the input source.
public int getDimension(int imageIndex)
throws IOException
MultidimensionalImageStore implementations provide a different value.
imageIndex - The image index.
IOException - if an error occurs reading the information from the input source.MultidimensionalImageStore
public GridEnvelope getGridEnvelope(int imageIndex)
throws IOException
getDimension(int),
ImageReader.getWidth(int) and ImageReader.getHeight(int) methods.
MultidimensionalImageStore implementations provide a different value.
imageIndex - The image index.
IOException - if an error occurs reading the information from the input source.MultidimensionalImageStore
public SpatialMetadata getStreamMetadata()
throws IOException
ImageReader.isIgnoringMetadata() is true, return null.createMetadata(-1)
and cache the result.
getStreamMetadata in class ImageReadernull if none.
IOException - if an error occurs during reading.
public SpatialMetadata getImageMetadata(int imageIndex)
throws IOException
checkImageIndex(imageIndex).ImageReader.isIgnoringMetadata() is true, return null.createMetadata(imageIndex)
and cache the result.
getImageMetadata in class ImageReaderimageIndex - The image index.
null if none.
IOException - if an error occurs during reading.
protected SpatialMetadata createMetadata(int imageIndex)
throws IOException
getStreamMetadata() and getImageMetadata(int) when the requested metadata
were not cached by a previous call, and ImageReader.isIgnoringMetadata() returns false.
The default implementation returns null if every cases. Subclasses should override
this method if they can provide metadata.
imageIndex - -1 for stream metadata, or the image index for image metadata.
null if none.
IOException - If an error occurred while reading metadata.
public boolean hasColors(int imageIndex)
throws IOException
true if the image at the given index has a color palette. Some formats like
RAW,
ASCII Grid or
NetCDF don't store any color
information with the pixel values, while other formats like PNG or JPEG (optionally wrapped
in a World File reader)
provide such color palette.
If this method returns false, no color information is included in the stream
to be read and users can provide their own color palette with a call to the
SpatialImageReadParam.setPaletteName(String) method. If this mehod returns
true, then the image to be read already have its own color information and
any call to the above-mentioned setPaletteName method are likely to be ignored.
The default implementation returns false in every cases. Subclasses shall override
this method if the implemented image format may have a color palette.
imageIndex - The index of the image to be queried.
true if the image at the given index has a color palette.
IOException - If an error occurs reading the information from the input source.SpatialImageReadParam.setPaletteName(String)
public Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex)
throws IOException
ImageTypeSpecifier containing possible image types to which
the given image may be decoded. The default implementation returns a singleton containing
getRawImageType(imageIndex).
getImageTypes in class ImageReaderimageIndex - The index of the image to be queried.
IOException - If an error occurs reading the format information from the input source.
public ImageTypeSpecifier getRawImageType(int imageIndex)
throws IOException
SampleModel and ColorModel
which most closely represents the "raw" internal format of the image. The default
implementation delegates to the following:
If this method needs to be overridden, consider overriding the later instead.return getImageType(imageIndex, getDefaultReadParam(), null);
getRawImageType in class ImageReaderimageIndex - The index of the image to be queried.
null).
IOException - If an error occurs reading the format information from the input source.getImageType(int, ImageReadParam, SampleConverter[]),
getDefaultReadParam()
protected ImageTypeSpecifier getImageType(int imageIndex,
ImageReadParam parameters,
SampleConverter[] converters)
throws IOException
SampleModel and ColorModel
to use for reading the image. In addition, this method also detects if some conversions
(represented by SampleConverter instances) are required in order to store the
sample values using the selected models. The conversions (if any) are keept as small as
possible, but are sometime impossible to avoid for example because IndexColorModel
does not allow negative sample values.
The default implementation applies the following steps:
The range of expected values and the fill values are extracted from the image metadata, if any.
If the given parameters argument is an instance of SpatialImageReadParam,
then the user-supplied palette name
is fetched. Otherwise or if no palette name was explicitly set, then this method default
to "grayscale". The
palette name will be used in order to read a predefined set of colors (as [A]RGB values) to be given to the
index color model.
If the raw data type is TYPE_FLOAT or TYPE_DOUBLE, then this method builds
a continuous palette suitable for
the range fetched at step 1. The data are assumed geophysics values
rather than some packed values. Consequently, the sample
converters will replace no-data values by NaN, but no other
changes will be applied.
Otherwise, if the raw data type is a unsigned integer type
like TYPE_BYTE or TYPE_USHORT,
then this method builds an indexed palette (i.e. a
palette backed by an index color model) with just the minimal
size needed for containing fully the range and the
no-data values fetched at step 1. The data are assumed packed values rather
than geophysics values. Consequently, the sample converters
will be the identity converter except in the
following cases:
collapseNoDataValues method.Otherwise, if the raw data type is a signed integer
type like TYPE_SHORT, then this method builds an
indexed palette with the maximal size supported by the raw data type (note that this is
memory expensive - typically 256 kilobytes). Negative values will be stored in their
two's complement binary form in order to fit in the range of positive integers
supported by the index color model.
Using the Sample Converters
If the converters argument is non-null, then this method will store the
SampleConverter instances in the supplied array. The array length shall be equals
to the number of source and
destination bands.
The converters shall be used by read method
implementations for converting the values read in the datafile to values acceptable
by the color model. See the
getDestination
method for code example.
Overriding this method
Subclasses can override this method for example if the color palette
and range of values should be computed in a different way. The example below creates an
image type using hard-coded objects:
int minimum = -2000; // Minimal expected value int maximum = +2300; // Maximal expected value int fillValue = -9999; // Value for missing data String colors = "rainbow"; // Named set of RGB colors converters[0] = SampleConverter.createOffset(1 - minimum, fillValue); Palette palette = PaletteFactory.getDefault().getPalettePadValueFirst(colors, maximum - minimum); return palette.getImageTypeSpecifier();
imageIndex - The index of the image to be queried.parameters - The user-supplied parameters, or null. Note: we recommend to supply
getDefaultReadParam() instead of null since subclasses may
override the later with default values suitable to a particular format.converters - If non-null, an array where to store the converters created by this method.
The length of this array shall be equals to the number of target bands.
null).
IOException - If an error occurs while reading the format information from the input source.getRawDataType(int),
collapseNoDataValues(boolean, double[], int),
getDestination(int, ImageReadParam, int, int, SampleConverter[])
protected int getRawDataType(int imageIndex)
throws IOException
DataBuffer TYPE_* constants. This information is used
by getImageType(...) in order
to create a default ImageTypeSpecifier.
The default SpatialImageReader implementation works better with
TYPE_BYTE,
TYPE_SHORT,
TYPE_USHORT and
TYPE_FLOAT.
Other types may work, but developers are advised to override the getImageType(...)
method as well.
The default implementation returns TYPE_FLOAT in every cases.
Special case for negative integer values (TYPE_SHORT)
If the sample values are integers but the range of valid values contains negative values, then strictly speaking this method should
return a signed type (TYPE_SHORT or TYPE_INT). If nevertheless this method return a unsigned type
(TYPE_BYTE or TYPE_USHORT), then
the default getImageType(...)
implementation will add an offset in order to fit all sample values in the range of strictly
positive values.
Example: if the range of sample values is [-23000 … +23000], then there
is a choice:
|
Beware that signed integers (case 1 in the above example) used with IndexColorModel
require explicit casts to the short type as in the example below. Using directly the
Raster.getSample(int,int,int) return value is not sufficient because
the returned value would be unsigned no matter what this getRawDataType(int) method
returned.
Given this gotcha and the fact that signed integers require large color palette, users are advised to prefer unsigned types if they can afford the offset applied on sample values.int value = (short) myRaster.getSample(x, y, b); // Intentional casts int → short → int.
imageIndex - The index of the image to be queried.
DataBuffer.TYPE_FLOAT by default).
IOException - If an error occurs reading the format information from the input source.getImageType(int, ImageReadParam, SampleConverter[]),
SampleConversionType.SHIFT_SIGNED_INTEGERS
protected boolean collapseNoDataValues(boolean isZeroValid,
double[] nodataValues,
int unusedSpace)
true if the no-data values should be collapsed to 0 in order to save memory.
This method is invoked automatically by the getImageType(...) method when it detected some unused space between the
range of valid values and at least one
no-data value.
The default implementation returns false in all cases, thus avoiding arbitrary
choice. Subclasses can override this method with some arbitrary threashold, as in the
example below:
return unusedSpace >= 1024;
isZeroValid - true if 0 is a valid value. If this method returns true while
isZeroValid is true, then the sample
converter to be returned by getImageType(...) will offset all valid values by 1.nodataValues - The sorted
no-data values (never null and never empty).unusedSpace - The largest amount of unused space outside the range of valid values.
true if the no-data values should be collapsed to 0 in order to save memory.
protected BufferedImage getDestination(int imageIndex,
ImageReadParam parameters,
int width,
int height,
SampleConverter[] converters)
throws IOException
BufferedImage, for example because IndexColorModel
does not support negative integers. The conversions (if any) are represented by
SampleConverter objects, which are computed as documented in the
getImageType method.
Using the Sample Converters
If the converters argument is non-null, then this method will store the
SampleConverter instances in the supplied array. The array length shall be equals
to the number of source and
destination bands.
The converters shall be used by read method
implementations for converting the values read in the datafile to values acceptable
by the color model.
Example (omitting the subsamplings
handling for simplicity):
public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException {
final int[] srcBands, dstBands;
if (param != null) {
srcBands = param.getSourceBands();
dstBands = param.getDestinationBands();
} else {
srcBands = null;
dstBands = null;
}
final int numSrcBands = (srcBands != null) ? srcBands.length : ...; // Image-dependant
final int numDstBands = (dstBands != null) ? dstBands.length : numSrcBands;
checkReadParamBandSettings(param, numSrcBands, numDstBands);
final int width = ...; // Image-dependant
final int height = ...; // Image-dependant
final SampleConverter[] converters = new SampleConverter[numDstBands];
final BufferedImage image = getDestination(imageIndex, param, width, height, converters);
final WritableRaster raster = image.getRaster();
final Rectangle srcRegion = new Rectangle();
final Rectangle destRegion = new Rectangle();
computeRegions(param, width, height, image, srcRegion, destRegion);
final int xmin = destRegion.x;
final int ymin = destRegion.y;
final int xmax = destRegion.width + xmin;
final int ymax = destRegion.height + ymin;
for (int band=0; band < numDstBands; band++) {
final int srcBand = (srcBands == null) ? band : srcBands[band];
final int dstBand = (dstBands == null) ? band : dstBands[band];
final SampleConverter converter = converters[band];
for (int y=ymin; y<ymax; y++) {
for (int x=xmin; x<xmax; x++) {
float value = ...; // Image-dependant
value = converter.convert(value);
raster.setSample(x, y, dstBand, value);
}
}
}
}
imageIndex - The index of the image to be retrieved.parameters - The parameter given to the read method.width - The true width of the image or tile begin decoded.height - The true width of the image or tile being decoded.converters - If non-null, an array where to store the converters required
for converting decoded pixel data into stored pixel data.
IOException - If an error occurs reading the format information from the input source.getImageType(int, ImageReadParam, SampleConverter[])public SpatialImageReadParam getDefaultReadParam()
SpatialImageReadParam.
getDefaultReadParam in class ImageReaderImageReadParam object which may be used.public boolean warningOccurred(LogRecord record)
warningOccurred method is
invoked for each of them and the log record is not logged."org.geotoolkit.image.io" logger.Subclasses may override this method if more processing is wanted, or for throwing exception if some warnings should be considered as fatal errors.
warningOccurred in interface WarningProducerrecord - The warning to log.
true if the message has been sent to at least one warning listener,
or false if it has been sent to the logging system as a fallback.MetadataNodeParser.warningOccurred(LogRecord)
protected void close()
throws IOException
super.close().
IOException - If an error occurred while closing a stream.public void dispose()
StreamImageReader or ImageReaderAdapter, it will be
closed before to dispose this reader.
dispose in interface Disposabledispose in class ImageReader
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD | |||||||||