\chapter{Image I/O: Reading Images}
\label{chap:imageinput}
\index{Image I/O API|(}


\section{Image Input Made Simple}
\label{sec:imageinput:simple}

Here is the simplest sequence required to open an image file, find
out its resolution, and read the pixels (converting them into
8-bit values in memory, even if that's not the way they're stored in the file):

\begin{code}
        #include <OpenImageIO/imageio.h>
        OIIO_NAMESPACE_USING
        ...

        ImageInput *in = ImageInput::open (filename);
        if (! in)
            return;
        const ImageSpec &spec = in->spec();
        int xres = spec.width;
        int yres = spec.height;
        int channels = spec.nchannels;
        std::vector<unsigned char> pixels (xres*yres*channels);
        in->read_image (TypeDesc::UINT8, &pixels[0]);
        in->close ();
        delete in;
\end{code}

\noindent Here is a breakdown of what work this code is doing:

\begin{itemize}
\item Search for an ImageIO plugin that is capable of reading the file
  (\qkw{foo.jpg}), first by trying to deduce the correct plugin from the
  file extension, but if that fails, by opening every ImageIO plugin it
  can find until one will open the file without error.  When it finds
  the right plugin, it creates a subclass instance of \ImageInput that
  reads the right kind of file format, and tries to fully open the file.
  \begin{code}
        ImageInput *in = ImageInput::open (filename);
  \end{code}
\item The specification, accessible as {\cf in->spec()}, contains 
  vital information such as the
  dimensions of the image, number of color channels, and data type of
  the pixel values.  This is enough to allow us to allocate enough space
  for the image.
  \begin{code}
        const ImageSpec &spec = in->spec();
        int xres = spec.width;
        int yres = spec.height;
        int channels = spec.nchannels;
        std::vector<unsigned char> pixels (xres*yres*channels);
  \end{code}
  Note that in this example, we don't care what data format is used for
  the pixel data in the file --- we allocate enough space for unsigned
  8-bit integer pixel values, and will rely on \product's ability to
  convert to our requested format from the native data format of the
  file.
\item Read the entire image, hiding all details of the encoding of image
  data in the file, whether the file is scanline- or tile-based, or what
  is the native format of the data in the file (in this case, we request
  that it be automatically converted to unsigned 8-bit integers).
  \begin{code}
        in->read_image (TypeDesc::UINT8, &pixels[0]);
  \end{code}
\item Close the file, destroy and free the \ImageInput we had created,
  and perform all other cleanup and release of any resources used by
  the plugin.
  \begin{code}
        in->close ();
        delete in;
  \end{code}
\end{itemize}



\section{Advanced Image Input}
\label{sec:advancedimageinput}

Let's walk through some of the most common things you might want to do,
but that are more complex than the simple example above.


\subsection{Reading individual scanlines and tiles}
\label{sec:imageinput:scanlinestiles}

The simple example of Section~\ref{sec:imageinput:simple} read an
entire image with one call.  But sometimes you want to read a large
image a
little at a time and do not wish to retain the entire image in memory
as you process it.  \product allows you to read images
one scanline at a time or one tile at a time.

Examining the \ImageSpec reveals whether the file is scanline or
tile-oriented: a scanline image will have {\cf spec.tile_width} 
and {\cf spec.tile_height} set to 0, whereas a tiled images will
have nonzero values for the tile dimensions.


\subsubsection{Reading scanlines}

Individual scanlines may be read using the \readscanline API
call:

\begin{code}
        ...
        in = ImageInput::open (filename);
        const ImageSpec &spec = in->spec();
        if (spec.tile_width == 0) {
            std::vector<unsigned char> scanline (spec.width*spec.channels);
            for (int y = 0;  y < yres;  ++y) {
                in->read_scanline (y, 0, TypeDesc::UINT8, &scanline[0]);
                ... process data in scanline[0..width*channels-1] ...
            }
        } else {
            ... handle tiles, or reject the file ...
        }
        in->close ();
        ...
\end{code}

The first two arguments to \readscanline specify which scanline
is being read by its vertical ($y$) scanline number (beginning with 0)
and, for volume images, its slice ($z$) number (the slice number should
be 0 for 2D non-volume images).  This is followed by a \TypeDesc
describing the data type of the pixel buffer you are supplying, and a
pointer to the pixel buffer itself.  Additional optional arguments
describe the data stride, which can be ignored for contiguous data (use
of strides is explained in Section~\ref{sec:imageinput:strides}).

Nearly all \ImageInput implementations will be most efficient reading
scanlines in strict order (starting with scanline 0, then 1, up to {\kw
  yres-1}, without skipping any).  An \ImageInput is required to accept
\readscanline requests in arbitrary order, but depending on the file
format and reader implementation, out-of-order scanline reads may be
inefficient.

There is also a {\cf read_scanlines()} function that operates similarly,
except that it takes a {\cf ybegin} and {\cf yend} that specify a range,
reading all scanlines {\cf ybegin} $\le y <$ {\cf yend}.  For most image
format readers, this is implemented as a loop over individual scanlines,
but some image format readers may be able to read a contiguous block of
scanlines more efficiently than reading each one individually.

The full descriptions of the \readscanline and {\cf read_scanlines()}
functions may be found in Section~\ref{sec:imageinput:reference}.

\subsubsection{Reading tiles}

Once you {\kw open()} an image file, you can find out if it is a tiled
image (and the tile size) by examining the \ImageSpec's {\cf
  tile_width}, {\cf tile_height}, and {\cf tile_depth} fields.
If they are zero, it's a scanline image and you should read pixels
using \readscanline, not \readtile.

\begin{code}
        ...
        in = ImageInput::open (filename);
        const ImageSpec &spec = in->spec();
        if (spec.tile_width == 0) {
            ... read by scanline ...
        } else {
            // Tiles
            int tilesize = spec.tile_width * spec.tile_height;
            std::vector<unsigned char> tile (tilesize * spec.channels);
            for (int y = 0;  y < yres;  y += spec.tile_height) {
                for (int x = 0;  x < xres;  x += spec.tile_width) {
                    in->read_tile (x, y, 0, TypeDesc::UINT8, &tile[0]);
                    ... process the pixels in tile[] ..
                }
            }
        }
        in->close ();
        ...
\end{code}

The first three arguments to \readtile specify which tile is
being read by the pixel coordinates of any pixel contained in the
tile: $x$ (column), $y$ (scanline), and $z$ (slice, which should always
be 0 for 2D non-volume images).  This is followed by a \TypeDesc
describing the data format of the pixel buffer you are supplying, and a
pointer to the pixel buffer.  Pixel data will be written to your buffer
in order of increasing slice, increasing
scanline within each slice, and increasing column within each scanline.
Additional optional arguments describe the data stride, which can be
ignored for contiguous data (use of strides is explained in
Section~\ref{sec:imageinput:strides}).

All \ImageInput implementations are required to support reading tiles in
arbitrary order (i.e., not in strict order of increasing $y$ rows, and
within each row, increasing $x$ column, without missing any tiles).

The full description of the \readtile function may be found
in Section~\ref{sec:imageinput:reference}.


\subsection{Converting formats}
\label{sec:imageinput:convertingformat}

The code examples of the previous sections all assumed that your
internal pixel data is stored as unsigned 8-bit integers (i.e., 0-255
range).  But \product is significantly more flexible.  

You may request that the pixels be stored in any of several formats.
This is done merely by passing the {\cf read} function the data type
of your pixel buffer, as one of the enumerated type \TypeDesc.

%FIXME
%Individual file formats, and therefore \ImageInput implementations, may
%only support a subset of the formats understood by the \product library.
%Each \ImageInput plugin implementation should document which data
%formats it supports.  An individual \ImageInput implementation may
%choose to simply fail open {\kw open()}, though the recommended behavior
%is for {\kw open()} to succeed but in fact choose a data format
%supported by the file format that best preserves the precision and range
%of the originally-requested data format.

It is not required that the pixel data buffer passed to \readimage,
\readscanline, or \readtile actually be in the same data format as the
data in the file being read.  \product will automatically convert from
native data type of the file to the internal data format of your choice.
For example, the following code will open a TIFF and read pixels into
your internal buffer represented as {\cf float} values.  This will work
regardless of whether the TIFF file itself is using 8-bit, 16-bit, or
float values.

\begin{code}
        ImageInput *in = ImageInput::open ("myfile.tif");
        const ImageSpec &spec = in->spec();
        ...
        int numpixels = spec.width * spec.height;
        float pixels = new float [numpixels * channels];
        ...
        in->read_image (TypeDesc::FLOAT, pixels);
\end{code}

\noindent Note that \readscanline and \readtile have a parameter that
works in a corresponding manner.

You can, of course, find out the native type of the file simply by
examining {\cf spec.format}.  If you wish, you may then allocate a
buffer big enough for an image of that type and request the native type
when reading, therefore eliminating any translation among types and
seeing the actual numerical values in the file.

%FIXME
%Please refer to Section~\ref{sec:imageinput:quantization} for more
%information on how values are translated among the supported data
%formats by default, and how to change the formulas by specifying
%quantization in the \ImageSpec.


\subsection{Data Strides}
\label{sec:imageinput:strides}

In the preceeding examples, we have assumed that the buffer passed to
the {\cf read} functions (i.e., the place where you want your pixels
to be stored) is \emph{contiguous}, that is:

\begin{itemize}
\item each pixel in memory consists of a number of data values equal to
  the number of channels in the file;
\item successive column pixels within a row directly follow each other in
  memory, with the first channel of pixel $x$ immediately following
  last channel of pixel $x-1$ of the same row;
\item for whole images or tiles, the data for each row
  immediately follows the previous one in memory (the first pixel of row
  $y$ immediately follows the last column of row $y-1$);
\item for 3D volumetric images, the first pixel of slice $z$ immediately
  follows the last pixel of of slice $z-1$.
\end{itemize}

Please note that this implies that \readtile will write pixel data into
your buffer so that it is contiguous in the shape of a single tile, not
just an offset into a whole image worth of pixels.

The \readscanline function takes an optional {\cf xstride} argument, and
the \readimage and \readtile functions take optional {\cf xstride}, 
{\cf ystride}, and {\cf zstride} values that describe the distance, in
\emph{bytes}, between successive pixel columns, rows, and slices,
respectively, of your pixel buffer.  For any of these values that are
not supplied, or are given as the special constant {\cf AutoStride},
contiguity will be assumed.

By passing different stride values, you can achieve some surprisingly
flexible functionality.  A few representative examples follow:

\begin{itemize}
\item Flip an image vertically upon reading, by using \emph{negative}
  $y$ stride:
  \begin{code}
    unsigned char pixels[spec.width * spec.height * spec.nchannels];
    int scanlinesize = spec.width * spec.nchannels * sizeof(pixels[0]);
    ...
    in->read_image (TypeDesc::UINT8,
                    (char *)pixels+(yres-1)*scanlinesize, // offset to last
                    AutoStride,                  // default x stride
                    -scanlinesize,               // special y stride
                    AutoStride);                 // default z stride
  \end{code}
\item Read a tile into its spot in a buffer whose layout matches
  a whole image of pixel data,
  rather than having a one-tile-only memory layout:
  \begin{code}
    unsigned char pixels[spec.width * spec.height * spec.nchannels];
    int pixelsize = spec.nchannels * sizeof(pixels[0]);
    int scanlinesize = xpec.width * pixelsize;
    ...
    in->read_tile (x, y, 0, TypeDesc::UINT8,
                   (char *)pixels + y*scanlinesize + x*pixelsize,
                   pixelsize,
                   scanlinesize);
  \end{code}
\end{itemize}

Please consult Section~\ref{sec:imageinput:reference} for detailed
descriptions of the stride parameters to each {\cf read} function.


\subsection{Reading metadata}
\label{sec:imageinput:metadata}

The \ImageSpec that is filled in by {\cf ImageInput::open()}
specifies all the common properties that describe an image: data format,
dimensions, number of channels, tiling.  However, there may be a variety
of additional \emph{metadata} that are present in the image file and
could be queried by your application.

The remainder of this section explains how to query additional metadata
in the \ImageSpec.  It is up to the \ImageInput to read these
from the file, if indeed the file format is able to carry additional
data.  Individual \ImageInput implementations should document which
metadata they read.

\subsubsection{Channel names}

In addition to specifying the number of color channels, the
\ImageSpec also stores the names of those channels in its {\cf
  channelnames} field, which is a {\cf vector<std::string>}.  Its length
should always be equal to the number of channels (it's the
responsibility of the \ImageInput to ensure this).

Only a few file formats (and thus \ImageInput implementations) have a
way of specifying custom channel names, so most of the time you will see
that the channel names follow the default convention of being named
\qkw{R}, \qkw{G}, \qkw{B}, and \qkw{A}, for red, green, blue, and alpha,
respectively.

Here is example code that prints the names of the channels in an image:

\begin{code}
        ImageInput *in = ImageInput::open (filename);
        const ImageSpec &spec = in->spec();
        for (int i = 0;  i < spec.nchannels;  ++i)
            std::cout << "Channel " << i << " is " 
                      << spec.channelnames[i] << "\n";
\end{code}

\subsubsection{Specially-designated channels}

The \ImageSpec contains two fields, {\cf alpha_channel} and {\cf
  z_channel}, which designate which channel numbers represent alpha and
$z$ depth, if any.  If either is set to {\cf -1}, it indicates that it
is not known which channel is used for that data.

If you are doing something special with alpha or depth, it is probably
safer to respect the {\cf alpha_channel} and {\cf z_channel}
designations (if not set to {\cf -1}) rather than merely assuming that,
for example, channel 3 is always the alpha channel.

\subsubsection{Arbitrary metadata}

All other metadata found in the file will be stored in the
\ImageSpec's {\cf extra_attribs} field, which is a 
\ParamValueList, which is itself essentially a vector of
\ParamValue instances.  Each \ParamValue
stores one meta-datum consisting of a name, type (specified by 
a \TypeDesc), number of values, and data pointer.

If you know the name of a specific piece of metadata you want to use,
you can find it using the {\cf ImageSpec::find_attribute()}
method, which returns a pointer to the matching \ParamValue,
or {\cf NULL} if no match was found.  An optional \TypeDesc
argument can narrow the search to only parameters that match the
specified type as well as the name.  Below is an
example that looks for orientation information, expecting it to consist 
of a single integer:

\begin{code}
        ImageInput *in = ImageInput::open (filename);
        const ImageSpec &spec = in->spec();
        ...
        ParamValue *p = spec.find_attribute ("Orientation", TypeDesc::TypeInt);
        if (p) {
            int orientation = * (int *) p->data();
        } else {
            std::cout << "No integer orientation in the file\n";
        }
\end{code}

By convention, \ImageInput plugins will save all integer metadata as
32-bit integers ({\cf TypeDesc::INT} or {\cf TypeDesc::UINT}), even if the file format
dictates that a particular item is stored in the file as a 8- or 16-bit
integer.  This is just to keep client applications from having to deal
with all the types.  Since there is relatively little metadata compared
to pixel data, there's no real memory waste of promoting all integer
types to int32 metadata.  Floating-point metadata and string metadata
may also exist, of course.

For certain common types, there is an even simpler method for retrieving
the metadata:

\begin{code}
    int i = spec.get_int_attribute ("Orientation", 0);
    float f = spec.get_float_attribute ("PixelAspectRatio", 1.0f);
    std::string s = spec.get_string_attribute ("ImageDescription", "");
\end{code}

This method simply returns the value.  The second argument is the
default value to use if the attribute named is not found.  These
versions will do automatic type conversion as well --- for example,
if you ask for a float and the attribute is really an int, it will 
return the proper float for it; or if the attribute is a UINT16 and
you call {\cf get_int_attribute}, it will succeed, promoting to an int.

It is also possible to step through all the metadata, item by item.
This can be accomplished using the technique of the following example:

\begin{code}
        for (size_t i = 0;  i < spec.extra_attribs.size();  ++i) {
            const ParamValue &p (spec.extra_attribs[i]);
            printf ("    \%s: ", p.name.c_str());
            if (p.type() == TypeDesc::TypeString)
                printf ("\"\%s\"", *(const char **)p.data());
            else if (p.type() == TypeDesc::TypeFloat)
                printf ("\%g", *(const float *)p.data());
            else if (p.type() == TypeDesc::TypeInt)
                printf ("\%d", *(const int *)p.data());
            else if (p.type() == TypeDesc::UINT)
                printf ("\%u", *(const unsigned int *)p.data());
            else if (p.type() == TypeDesc::TypeMatrix) {
                const float *f = (const float *)p.data();
                printf ("\%f \%f \%f \%f \%f \%f \%f \%f "
                        "\%f \%f \%f \%f \%f \%f \%f \%f",
                        f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7],
                        f[8], f[9], f[10], f[11], f[12], f[13], f[14], f[15]);
            }
            else
                printf ("<unknown data type>");
            printf ("\n");
        }
\end{code}

Each individual \ImageInput implementation should document the names,
types, and meanings of all metadata attributes that they understand.

\subsubsection{Color space hints}

We certainly hope that you are using only modern file formats that
support high precision and extended range pixels (such as OpenEXR) and
keeping all your images in a linear color space.  But you may have to
work with file formats that dictate the use of nonlinear color values.
This is prevalent in formats that store pixels only as 8-bit values,
since 256 values are not enough to linearly represent colors without
banding artifacts in the dim values.

The {\cf ImageSpec::extra_attribs} field may store metadata that reveals
the color space the image file in the \qkw{oiio:ColorSpace}
attribute, which may take on any of the following values:

\begin{description}
\item[\halfspc \rm \qkw{Linear}] indicates that the
  color pixel values are known to be linear.
\item[\halfspc \rm \qkw{GammaCorrected}] indicates
  that the color pixel values (but not alpha or $z$) have
  already been gamma corrected (raised to the power $1/\gamma$), and
  that the gamma exponent may be found in the \qkw{oiio:Gamma} metadata.
\item[\halfspc \rm \qkw{sRGB}] indicates that the
  color pixel values are in sRGB color space.
\item[\halfspc \rm \qkw{AdobeRGB}] indicates that the
  color pixel values are in Adobe RGB color space.
\item[\halfspc \rm \qkw{Rec709}] indicates that the
  color pixel values are in Rec709 color space.
\item[\halfspc \rm \qkw{KodakLog}] indicates that the
  color pixel values are in Kodak logarithmic color space.
\end{description}

The \ImageInput sets the \qkw{oiio:ColorSpace} metadata in a
purely advisory capacity --- the {\cf read} will not convert pixel
values among color spaces.  Many image file formats only support
nonlinear color spaces (for example, JPEG/JFIF dictates use of sRGB).
So your application should intelligently deal with gamma-corrected and
sRGB input, at the very least.

The color space hints only describe color channels.  You should assume that
alpha or depth ($z$) channels (designated by the {\cf alpha_channel} and
{\cf z_channel} fields, respectively) always represent linear values and
should never be transformed by your application.


%\subsection{Controlling quantization and encoding}
%\label{sec:imageinput:quantization}
%
%FIXME


%\subsection{Random access and repeated transmission of pixels}
%\label{sec:imageinput:randomrepeated}
%
%FIXME


\subsection{Multi-image files and MIP-maps}
\label{sec:imageinput:multiimage}
\label{sec:imageinput:mipmap}

Some image file formats support multiple discrete subimages to be stored
in one file, and/or miltiple resolutions for each image to form a
MIPmap.  When you {\cf open()} an \ImageInput, it will by default point
to the first (i.e., number 0) subimage in the file, and the highest
resolution (level 0) MIP-map level.  You can switch to viewing another
subimage or MIP-map level using the {\cf seek_subimage()} function:

\begin{code}
        ImageInput *in = ImageInput::open (filename);
        const ImageSpec &spec = in->spec();
        ...
        int subimage = 1;
        int miplevel = 0;
        if (in->seek_subimage (subimage, miplevel, spec)) {
            ...
        } else {
            ... no such subimage/miplevel ...
        }
\end{code}

The {\cf seek_subimage()} function takes three arguments: the index of
the subimage to switch to (starting with 0), the MIPmap level (starting
with 0 for the highest-resolution level), and a reference to an
\ImageSpec, into which will be stored the spec of the new
subimage/miplevel.  The {\cf seek_subimage()} function returns {\cf
  true} upon success, and {\cf false} if no such subimage or MIP level
existed.  It is legal to visit subimages and MIP levels out of order;
the \ImageInput is responsible for making it work properly.  It is also
possible to find out which subimage and MIP level is currently being
viewed, using the {\cf current_subimage()} and {\cf current_miplevel()}
functions, which return the index of the current subimage and MIP
levels, respectively.

Below is pseudocode for reading all the levels of a MIP-map (a
multi-resolution image used for texture mapping) that shows how to read
multi-image files:

\begin{code}
        ImageInput *in = ImageInput::open (filename);
        const ImageSpec &spec = in->spec();

        int num_miplevels = 0;
        while (in->seek_subimage (0, num_miplevels, spec)) {
            // Note: spec has the format of the current subimage/miplevel
            int npixels = spec.width * spec.height;
            int nchannels = spec.nchannels;
            unsigned char *pixels = new unsigned char [npixels * nchannels];
            in->read_image (TypeDesc::UINT8, pixels);

            ... do whatever you want with this level, in pixels ...

            delete [] pixels;
            ++num_miplevels;
        }
        // Note: we break out of the while loop when seek_subimage fails
        // to find a next MIP level.

        in->close ();
        delete in;
\end{code}

In this example, we have used \readimage, but of course \readscanline
and \readtile work as you would expect, on the current subimage and MIP
level.


\subsection{Per-channel formats}
\label{sec:imageinput:channelformats}

Some image formats allow separate per-channel data formats (for example,
{\cf half} data for colors and {\cf float} data for depth).  If you want
to read the pixels in their true native per-channel formats,
the following steps are necessary:

\begin{enumerate}
\item Check the \ImageSpec's {\cf channelformats} vector.  If non-empty,
  the channels in the file do not all have the same format.
\item When calling {\cf read_scanline}, {\cf read_scanlines},
  {\cf read_tile}, {\cf read_tiles}, or {\cf read_image}, 
  pass a format of {\cf TypeDesc::UNKNOWN} to indicate that
  you would like the raw data in native per-channel format of the file
  written to your {\cf data} buffer.
\end{enumerate}

For example, the following code fragment will read a 5-channel image
to an OpenEXR file, consisting of R/G/B/A channels in {\cf half} and
a Z channel in {\cf float}:

\begin{code}
        ImageInput *in = ImageInput::open (filename);
        const ImageSpec &spec = in->spec();

        // Allocate enough space
        unsigned char *pixels = new unsigned char [spec.image_bytes(true)];

        in->read_image (TypeDesc::UNKNOWN, /* use native channel formats */
                        pixels);           /* data buffer */

        if (spec.channelformats.size() > 0) {
            ... the buffer contains packed data in the native 
                per-channel formats ...
        } else {
            ... the buffer contains all data per spec.format ...
        }
\end{code}


\subsection{Reading ``deep'' data}
\label{sec:imageinput:deepdata}  \index{deep data}
Some image file formats (OpenEXR only, at this time) support the concept
of ``deep'' pixels -- those containing multiple samples per pixel (and a
potentially differing number of them in each pixel).
You can tell an image is ``deep'' from its \ImageSpec: the {\cf deep}
field will be {\cf true}.

Deep files cannot be read with the usual {\cf read_scanline}, {\cf
  read_scanlines}, {\cf read_tile}, {\cf read_tiles}, {\cf read_image}
functions, due to the nature of their variable number of samples per
pixel.  Instead, \ImageInput has three special member functions used
only for reading deep data:

\begin{code}
    bool read_native_deep_scanlines (int ybegin, int yend, int z,
                                     int chbegin, int chend,
                                     DeepData &deepdata);

    bool read_native_deep_tiles (int xbegin, int xend, int ybegin, int yend,
                                 int zbegin, int zend,
                                 int chbegin, int chend, DeepData &deepdata);

    bool read_native_deep_image (DeepData &deepdata);
\end{code}

It is only possible to read ``native'' data types from deep files; that
is, there is no automatic translation into arbitrary data types as there
is for ordinary images.  All three of these functions store the
resulting deep data in a special {\cf DeepData} structure, defined in
{\cf imageio.h} as follows:

\begin{code}
    struct DeepData {
        int npixels, nchannels;
        std::vector<TypeDesc> channeltypes;  // for each channel [c]
        std::vector<unsigned int> nsamples;// for each pixel [z][y][x]
        std::vector<void *> pointers;    // for each channel per pixel [z][y][x][c]
        std::vector<char> data;          // for each sample [z][y][x][c][s]

        DeepData ();
        // Set the size and allocate the nsamples[] vector.
        void init (int npix, int nchan,
                   const TypeDesc *chbegin, const TypeDesc *chend);
        // After nsamples[] has been filled in, allocate enough scratch space
        // for data and set up all the pointers.
        void alloc ();
        // Clear the vectors and reset size to 0.
        void clear ();
        // Deallocate all space in the vectors
        void free ();
        // Retrieve the pointer to the first sample of the given pixel and
        // channel. Return NULL if there are no samples for that pixel.
        void *channel_ptr (int pixel, int channel) const;
        // Retrieve sample value within a pixel, cast to a float.
        float deep_value (int pixel, int channel, int sample) const;
    };
\end{code}

Here is an example of using these methods to read a deep image from 
a file and print all its values:

\begin{code}
    ImageInput *in = ImageInput::open (filename);
    if (! in)
        return;
    const ImageSpec &spec = in->spec();
    if (spec.deep) {
        DeepData deepdata;
        in->read_native_deep_image (deepdata);
        int p = 0;  // absolute pixel number
        for (int y = 0; y < spec.height;  ++y) {
            for (int x = 0;  x < spec.width;  ++x) {
                std::cout << "Pixel " << x << "," << y << ":\n";
                if (deepdata.nsamples[p] == 0)
                    std::cout << "  no samples\n";
                else
                    for (int c = 0;  c < spec.nchannels;  ++c) {
                        TypeDesc type = deepdata.channeltypes[c];
                        std::cout << "  " << spec.channelnames[c] << ": ";
                        void *ptr = deepdata.pointers[p*spec.nchannels+c]
                        for (int s = 0;  s < deepdata.nsamples[p];  ++s) {
                            if (type.basetype == TypeDesc::FLOAT)
                                std::cout << ((float *)ptr)[s] << ' ';
                            else if (type.basetype == TypeDesc::HALF)
                                std::cout << ((half *)ptr)[s] << ' ';
                            ... handle other types ...
                        }
                        std::cout << "\n";
                    }
            }
        }
    }
    in->close ();
    delete in;
\end{code}


\subsection{Custom search paths for plugins}
\label{sec:imageinput:searchpaths}

Please see Section~\ref{sec:miscapi} for discussion
about setting the plugin search path via the {\cf attribute()} function.
For example:

\begin{code}
        std::string mysearch = "/usr/myapp/lib:${HOME}/plugins";
        OpenImageIO::attribute ("plugin_searchpath", mysearch);
        ImageInput *in = ImageInput::open (filename);
        ...
\end{code} %$


\subsection{Error checking}
\label{sec:imageinput:errors}
\index{error checking}

Nearly every \ImageInput API function returns a {\cf bool} indicating
whether the operation succeeded ({\cf true}) or failed ({\cf false}).
In the case of a failure, the \ImageInput will have saved an error
message describing in more detail what went wrong, and the latest
error message is accessible using the \ImageInput method 
{\cf geterror()}, which returns the message as a {\cf std::string}.

The exceptions to this rule are static methods such as the static
{\cf ImageInput::open} and {\cf ImageInput::create}, which return
{\cf NULL} if it could not create an appropriate \ImageInput (and open
it, in the case of {\cf open()}.  In such a case,
since no \ImageInput is returned for which you can call its {\cf
  geterror()} function, there exists a global {\cf geterror()}
function (in the {\cf OpenImageIO} namespace) that retrieves the latest
error message resulting from a call to static {\cf open()} or {\cf create()}.

Here is another version of the simple image reading code from
Section~\ref{sec:imageinput:simple}, but this time it is fully
elaborated with error checking and reporting:

\begin{code}
        #include <OpenImageIO/imageio.h>
        OIIO_NAMESPACE_USING
        ...

        const char *filename = "foo.jpg";
        int xres, yres, channels;
        std::vector<unsigned char> pixels;

        ImageInput *in = ImageInput::open (filename);
        if (! in) {
            std::cerr << "Could not open " << filename 
                      << ", error = " << OpenImageIO::geterror() << "\n";
            return;
        }
        const ImageSpec &spec = in->spec();
        xres = spec.width;
        yres = spec.height;
        channels = spec.nchannels;
        pixels.resize (xres*yres*channels);

        if (! in->read_image (TypeDesc::UINT8, pixels)) {
            std::cerr << "Could not read pixels from " << filename 
                      << ", error = " << in->geterror() << "\n";
            delete in;
            return;
        }

        if (! in->close ()) {
            std::cerr << "Error closing " << filename 
                      << ", error = " << in->geterror() << "\n";
            delete in;
            return;
        }
        delete in;
\end{code}


\newpage
\section{\ImageInput Class Reference}
\label{sec:imageinput:reference}

\apiitem{ImageInput * {\ce open} (const std::string \&filename, \\
\bigspc\bigspc const ImageSpec *config=NULL)}
Create an \ImageInput subclass instance that is able to read
the given file and open it, returning the opened \ImageInput if
successful.  If it fails, return {\cf NULL} and set an error that can
be retrieved by {\cf OpenImageIO::geterror()}.
    
The {\cf config}, if not {\cf NULL}, points to an \ImageSpec giving
requests or special instructions.  \ImageInput implementations
are free to not respond to any such requests, so the default
implementation is just to ignore config.
    
The {\cf open()} function will first try to make an \ImageInput
corresponding to the format implied by the file extension (for example,
\qkw{foo.tif} will try the TIFF plugin), but if one is not found or if
the inferred one does not open the file, every known \ImageInput type
will be tried until one is found that will open the file.
\apiend

\apiitem{ImageInput * {\ce create} (const std::string \&filename, \\
\bigspc\bigspc   const std::string \&plugin_searchpath="")}

Create and return an \ImageInput implementation that is able
to read the given file.  The {\kw plugin_searchpath} parameter is a
colon-separated list of directories to search for \product plugin
DSO/DLL's (not a searchpath for the image itself!).  This will
actually just try every ImageIO plugin it can locate, until it
finds one that's able to open the file without error.  This just
creates the \ImageInput, it does not open the file.
\apiend

\apiitem{const char * {\ce format_name} (void) const}
Return the name of the format implemented by this class.
\apiend

\apiitem{bool {\ce supports} (const std::string \&feature)}
\label{sec:inputsupportsfeaturelist}
Given the name of a \emph{feature}, tells if this \ImageInput 
instance supports that feature.  The following features are recognized
by this query:
\begin{description}
\item[\spc] \spc
\item[\rm ] No queries supported at this time.
\end{description}
\apiend

\apiitem{bool {\ce valid_file} (const std::string \&filename) const}
Return {\cf true} if the named file is a file of the type for this
\ImageInput.  The implementation will try to determine this as
efficiently as possible, in most cases much less expensively than doing
a full {\cf open()}.  Note that a file can appear to be of
the right type (i.e., {\cf valid_file()} returning {\cf true}) but still
fail a subsequent call to {\cf open()}, such as if the contents of the
file are truncated, nonsensical, or otherwise corrupted.
\apiend

\apiitem{bool {\ce open} (const std::string \&name, ImageSpec \&newspec)}
Opens the file with given name and seek to the first subimage in the
file.  Various file attributes are put in
{\kw newspec} and a copy is also saved internally to the
\ImageInput (retrievable via {\kw spec()}.  From examining
{\kw newspec} or {\kw spec()}, you can discern the resolution, if it's
tiled, number of channels, native data format, and other metadata about
the image.  Return {\kw true} if the file was found and opened okay,
otherwise {\kw false}.
\apiend

\apiitem{bool {\ce open} (const std::string \&name, ImageSpec \&newspec,\\
\bigspc  const ImageSpec \&config)}

Opens the file with given name, similarly to {\cf open(name, newspec)}.
However, in this version, any non-default fields of {\cf config},
including metadata, will be taken to be configuration requests,
preferences, or hints.  The default implementation of 
{\cf open (name, newspec, config)} will simply ignore {\cf config} and
calls the usual {\cf open (name, newspec)}.  But a plugin may choose to
implement this version of {\cf open} and respond in some way to the
configuration requests.  Supported configuration requests should be
documented by each plugin.
\apiend

\apiitem {const ImageSpec \& {\ce spec} (void) const}
Returns a reference to the image format specification of the
current subimage.  Note that the contents of the spec are
invalid before {\kw open()} or after {\kw close()}.
\apiend

\apiitem{bool {\ce close} ()}
Closes an open image.
\apiend


\apiitem{int {\ce current_subimage} (void) const}
Returns the index of the subimage that is currently being read.
The first subimage (or the only subimage, if there is just one) is
number 0.
\apiend


\apiitem{bool {\ce seek_subimage} (int subimage, int miplevel, ImageSpec \&newspec)}

Seek to the given subimage and MIP-map level within the open image file.
The first subimage in the file has index 0, and for each subimage, the
highest-resolution MIP level has index 0.  Return {\kw true} on success,
{\kw false} on failure (including that there is not a subimage or MIP
level with those indices).  The new subimage's vital statistics are put
in {\kw newspec} (and also saved internally in a way that can be
retrieved via {\kw spec()}).  The \ImageInput is expected to give the
appearance of random access to subimages and MIP levels --- in other
words, if it can't randomly seek to the given subimage or MIP level, it
should transparently close, reopen, and sequentially read through prior
subimages and levels.

\apiend

\apiitem{bool {\ce read_scanline} (int y, int z, TypeDesc format, void *data,\\
  \bigspc\spc\spc                      stride_t xstride=AutoStride)}

Read the scanline that includes pixels $(*,y,z)$ into {\kw data}
($z=0$ for non-volume images),
converting if necessary from the native data format of the file into the
{\kw format} specified.
If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data will be preserved 
in its native format (including per-channel formats, if applicable).
The {\kw xstride}
value gives the data spacing of adjacent pixels (in bytes).  Strides set
to the special value {\kw AutoStride} imply contiguous data, i.e., \\
  \spc {\kw xstride} $=$ {\kw spec.nchannels * spec.pixel_size()} \\
The \ImageInput is expected to give the appearance of random access
--- in other words, if it can't randomly seek to the given scanline, it
should transparently close, reopen, and sequentially read through prior
scanlines.  The base \ImageInput class has a default implementation
that calls {\kw read_native_scanline()} and then does appropriate format
conversion, so there's no reason for each format plugin to override this
method.
\apiend

\apiitem{bool {\ce read_scanline} (int y, int z, float *data)}
This simplified version of {\kw read_scanline()} reads to contiguous 
float pixels.
\apiend

\apiitem{bool {\ce read_scanlines} (int ybegin, int yend, int z,\\
  \bigspc TypeDesc format, void *data,\\
  \bigspc stride_t xstride=AutoStride, stride_t ystride=AutoStride) \\
bool {\ce read_scanlines} (int ybegin, int yend, int z,\\
  \bigspc int chbegin, int chend, TypeDesc format, void *data,\\
  \bigspc                      stride_t xstride=AutoStride, stride_t ystride=AutoStride)}

Read all the scanlines that include pixels $(*,y,z)$, where
$\mathit{ybegin} \le y < \mathit{yend}$, into {\kw data}.  This is 
essentially identical to \readscanline, except that can read more than
one scanline at a time, which may be more efficient for certain image
format readers.

The version that specifies a channel range will read only
channels $[${\cf chbegin},{\cf chend}$)$ into the buffer.
\apiend


\apiitem{bool {\ce read_tile} (int x, int y, int z, TypeDesc format,
                            void *data, \\ \bigspc stride_t xstride=AutoStride,
                            stride_t ystride=AutoStride, \\ \bigspc stride_t
                            zstride=AutoStride)}
Read the tile whose upper-left origin is $(x,y,z)$ into {\kw data}
($z=0$ for non-volume images),
converting if necessary from the native data format of the file into the 
{\kw format} specified.
If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data will be preserved 
in its native format (including per-channel formats, if applicable).
The stride values
give the data spacing of adjacent pixels, scanlines, and volumetric
slices, respectively (measured in bytes).  Strides set to the special
value of {\kw AutoStride} imply contiguous data, i.e., \\
\spc {\kw xstride} $=$ {\kw spec.nchannels * spec.pixel_size()} \\
\spc {\kw ystride} $=$ {\kw xstride * spec.tile_width} \\
\spc {\kw zstride} $=$ {\kw ystride * spec.tile_height} \\
The \ImageInput is expected to give the appearance of random access
--- in other words, if it can't randomly seek to the given tile, it
should transparently close, reopen, and sequentially read through prior
tiles.  The base \ImageInput class has a default implementation
that calls {\cf read_native_tile()} and then does appropriate format conversion,
so there's no reason for each format plugin to override this method.

This function returns {\cf true} if it successfully reads the tile,
otherwise {\cf false} for a failure.
The call will fail if the image is not tiled, or if $(x,y,z)$ is not
actually a tile boundary.
\apiend


\apiitem{bool {\ce read_tile} (int x, int y, int z, float *data)}
Simple version of {\kw read_tile} that reads to contiguous float pixels.
\apiend


\apiitem{bool {\ce read_tiles} (int xbegin, int xend, int ybegin, int
  yend, \\ \bigspc int zbegin, int zend, TypeDesc format,
                            void *data, \\ \bigspc stride_t xstride=AutoStride,
                            stride_t ystride=AutoStride, \\ \bigspc stride_t
                            zstride=AutoStride) \\
bool {\ce read_tiles} (int xbegin, int xend, int ybegin, int yend, \\
 \bigspc int zbegin, int zend, int chbegin, int chend,\\
 \bigspc TypeDesc format, void *data, \\ 
 \bigspc stride_t xstride=AutoStride, stride_t ystride=AutoStride, \\
 \bigspc stride_t zstride=AutoStride)}
Read the tiles bounded by {\kw xbegin} $\le x <$ {\kw xend},
{\kw ybegin} $\le y <$ {\kw yend}, {\kw zbegin} $\le z <$ {\kw zend}
into {\kw data}
converting if necessary from the file's native data format into
the specified buffer {\kw format}.
If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data will be preserved 
in its native format (including per-channel formats, if applicable).
The stride values
give the data spacing of adjacent pixels, scanlines, and volumetric
slices, respectively (measured in bytes).  Strides set to the special
value of {\kw AutoStride} imply contiguous data, i.e., \\
\spc {\kw xstride} $=$ {\kw spec.nchannels * spec.pixel_size()} \\
\spc {\kw ystride} $=$ {\kw xstride * spec.tile_width} \\
\spc {\kw zstride} $=$ {\kw ystride * spec.tile_height} \\
The \ImageInput is expected to give the appearance of random access
--- in other words, if it can't randomly seek to the given tile, it
should transparently close, reopen, and sequentially read through prior
tiles.  The base \ImageInput class has a default implementation
that calls {\cf read_native_tiles()} and then does appropriate format conversion,
so there's no reason for each format plugin to override this method.

This function returns {\cf true} if it successfully reads the tiles,
otherwise {\cf false} for a failure.
The call will fail if the image is not tiled, or if the pixel ranges
do not fall along tile (or image) boundaries, or if it is not a valid
tile range.

The version that specifies a channel range will read only
channels $[${\cf chbegin},{\cf chend}$)$ into the buffer.
\apiend


\apiitem{bool {\ce read_image} (TypeDesc format, void *data, \\
                             \bigspc stride_t xstride=AutoStride,
                             stride_t ystride=AutoStride, \\
                             \bigspc stride_t zstride=AutoStride, \\
                             \bigspc ProgressCallback progress_callback=NULL,\\
                             \bigspc void *progress_callback_data=NULL)}

Read the entire image of {\kw spec.width * spec.height * spec.depth}
pixels into data (which must already be sized large enough for
the entire image) with the given strides, converting into the desired
data format.  
If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data will be preserved 
in its native format (including per-channel formats, if applicable).
This function will automatically handle either tiles or scanlines in
the file.

Strides set to the special value of {\kw AutoStride} imply contiguous
data, i.e., \\
\spc {\kw xstride} $=$ {\kw spec.nchannels * pixel_size()} \\
\spc {\kw ystride} $=$ {\kw xstride * spec.width} \\
\spc {\kw zstride} $=$ {\kw ystride * spec.height} \\
The function will internally either call {\kw read_scanlines} or 
{\kw read_tiles}, depending on whether the file is scanline- or
tile-oriented.

Because this may be an expensive operation, a progress callback may be passed.
Periodically, it will be called as follows:\\
\begin{code}
    progress_callback (progress_callback_data, float done)
\end{code}
\noindent where \emph{done} gives the portion of the image 
(between 0.0 and 1.0) that has been read thus far.
\apiend

\apiitem{bool {\ce read_image} (float *data)}
Simple version of {\kw read_image()} reads to contiguous float pixels.
\apiend

\apiitem{bool {\ce read_native_scanline} (int y, int z, void *data)}
The {\kw read_native_scanline()} function is just like {\kw
  read_scanline()}, except that it keeps the data in the native format
of the disk file and always reads into contiguous memory (no strides).
It's up to the user to have enough space allocated and know what to do
with the data.  IT IS EXPECTED THAT EACH FORMAT PLUGIN WILL OVERRIDE
THIS METHOD.
\apiend

\apiitem{bool {\ce read_native_scanlines} (int ybegin, int yend, int z, void *data)}
The {\kw read_native_scanlines()} function is just like 
{\cf read_native_scanline}, except that it reads
a range of scanlines rather than only one scanline.  It is not necessary
for format plugins to override this method --- a default implementation
in the \ImageInput base class simply calls {\cf read_native_scanline}
for each scanline in the range.  But format plugins may optionally
override this method if there is a way to achieve higher performance by
reading multiple scanlines at once.
\apiend

\apiitem{bool {\ce read_native_scanlines} (int ybegin, int yend, int z,
\\ \bigspc  int chbegin, int chend, void *data)}
A variant of {\cf read_native_scanlines} that reads only a subset of 
channels \\ $[${\cf chbegin},{\cf chend}$)$.  
If a format reader subclass does
not override this method, the default implementation will simply
call the all-channel version of {\cf read_native_scanlines} into a
temporary buffer and copy the subset of channels.
\apiend

\apiitem{bool {\ce read_native_tile} (int x, int y, int z, void *data)}
The {\kw read_native_tile()} function is just like {\kw read_tile()}, 
except that it keeps the data in the native format of the disk file and
always read into contiguous memory (no strides).  It's up to the user to
have enough space allocated and know what to do with the data.  IT IS
EXPECTED THAT EACH FORMAT PLUGIN WILL OVERRIDE THIS METHOD IF IT
SUPPORTS TILED IMAGES.
\apiend

\apiitem{bool {\ce read_native_tiles} (int xbegin, int xend, int ybegin,
  int yend, \\ \bigspc int zbegin, int zend, void *data)}
The {\kw read_native_tiles()} function is just like {\kw read_tiles()}, 
except that it keeps the data in the native format of the disk file and
always read into contiguous memory (no strides).  
If a format reader does not override this method, the default
implementation it will simply be a loop calling read_native_tile
for each tile in the block.
\apiend

\apiitem{bool {\ce read_native_tiles} (int xbegin, int xend, int ybegin,
  int yend, \\ \bigspc int zbegin, int zend, int chbegin, int chend, void *data)}
A variant of {\kw read_native_tiles()} that reads only a subset of 
channels \\ $[${\cf chbegin},{\cf chend}$)$.  
If a format reader subclass does
not override this method, the default implementation will simply
call the all-channel version of {\cf read_native_tiles} into a
temporary buffer and copy the subset of channels.
\apiend

\apiitem{bool {\ce read_native_deep_scanlines} (int ybegin, int yend, int z,
 \\ \bigspc   int chbegin, int chend, DeepData \&deepdata) \\
bool {\ce read_native_deep_tiles} (int xbegin, int xend,
                                         int ybegin, int yend, \\ \bigspc
                                         int zbegin, int zend,
                                         int chbegin, int chend,
                                         DeepData \&deepdata) \\
bool {\ce read_native_deep_image} (DeepData \&deepdata)}
Read native deep data from scanlines, tiles, or an entire image, 
storing the results in {\cf deepdata} (analogously to the usual
{\cf read_scanlines}, {\cf read_tiles},
and {\cf read_image}, but with deep data).
Only channels $[${\cf chbegin},{\cf chend}$)$
will be read.
\apiend

\apiitem{int {\ce send_to_input} (const char *format, ...)}
General message passing between client and image input server.
This is currently undefined and is reserved for future use.
\apiend

\apiitem{int {\ce send_to_client} (const char *format, ...)}
General message passing between client and image input server.
This is currently undefined and is reserved for future use.
\apiend

\apiitem{std::string {\ce geterror} () const}
\index{error checking}
Returns the current error string describing what went wrong if
any of the public methods returned {\kw false} indicating an error.
(Hopefully the implementation plugin called {\kw error()} with a
helpful error message.)
\apiend



\index{Image I/O API|)}

\chapwidthend
