1\chapter{ImageOutput: Writing Images}
2\label{chap:imageoutput}
3\index{Image I/O API|(}
4\indexapi{ImageOutput}
5
6
7\section{Image Output Made Simple}
8\label{sec:imageoutput:simple}
9
10Here is the simplest sequence required to write the pixels of a 2D image
11to a file:
12
13\begin{code}
14        #include <OpenImageIO/imageio.h>
15        using namespace OIIO;
16        ...
17
18        const char *filename = "foo.jpg";
19        const int xres = 640, yres = 480;
20        const int channels = 3;  // RGB
21        unsigned char pixels[xres*yres*channels];
22
23        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
24        if (! out)
25            return;
26        ImageSpec spec (xres, yres, channels, TypeDesc::UINT8);
27        out->open (filename, spec);
28        out->write_image (TypeDesc::UINT8, pixels);
29        out->close ();
30\end{code}
31
32\noindent This little bit of code does a surprising amount of useful work:
33
34\begin{itemize}
35\item Search for an ImageIO plugin that is capable of writing the file
36  (\qkw{foo.jpg}), deducing the format from the file extension.  When it
37  finds such a plugin, it creates a subclass instance of \ImageOutput
38  that writes the right kind of file format.
39  \begin{code}
40        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
41  \end{code}
42\item Open the file, write the correct headers, and in all other
43  important ways prepare a file with the given dimensions ($640 \times
44  480$), number of color channels (3), and data format (unsigned 8-bit
45  integer).
46  \begin{code}
47        ImageSpec spec (xres, yres, channels, TypeDesc::UINT8);
48        out->open (filename, spec);
49  \end{code}
50\item Write the entire image, hiding all details of the encoding of
51  image data in the file, whether the file is scanline- or tile-based,
52  or what is the native format of data in the file (in this case, our
53  in-memory data is unsigned 8-bit and we've requested the same format
54  for disk storage, but if they had been different, {\kw write_image()}
55  would do all the conversions for us).
56  \begin{code}
57        out->write_image (TypeDesc::UINT8, &pixels);
58  \end{code}
59\item Close the file.
60  \begin{code}
61        out->close ();
62  \end{code}
63\end{itemize}
64
65\subsection*{What happens when the file format doesn't support the spec?}
66
67The {\cf open()} call will fail (returning an empty pointer and set an appropriate
68error message) if the output format cannot accommodate what is requested by
69the \ImageSpec. This includes:
70\begin{itemize}
71\item Dimensions (width, height, or number of channels) exceeding the limits
72  supported by the file format.\footnote{One exception to the rule about
73  number of channels is that a file format that supports only RGB, but not
74  alpha, is permitted to silently drop the alpha channel without considering
75  that to be an error.}
76\item Volumetric (depth $> 1$) if the format does not support volumetric
77  data.
78\item Tile size $>1$ if the format does not support tiles.
79\item Multiple subimages or MIP levels if not supported by the format.
80\end{itemize}
81
82
83However, several other mismatches between requested \ImageSpec and file
84format capabilities will be silently ignored, allowing {\cf open()} to
85succeed:
86
87\begin{itemize}
88\item If the pixel data format is not supported (for example, a request for
89  {\cf half} pixels when writing a JPEG/JFIF file), the format writer
90  may substitute another data format (generally, whichever commonly-used
91  data format supported by the file type will result in the least reduction
92  of precision or range).
93\item If the \ImageSpec requests different per-channel data formats, but
94  the format supports only a single format for all channels, it may just
95  choose the most precise format requested and use it for all channels.
96\item If the file format does not support arbitrarily-named channels, the
97  channel names may be lost when saving the file.
98\item Any other metadata in the \ImageSpec may be summarily dropped if not
99  supported by the file format.
100\end{itemize}
101
102
103\section{Advanced Image Output}
104\label{sec:imageoutput:advanced}
105
106Let's walk through many of the most common things you might want to do,
107but that are more complex than the simple example above.
108
109\subsection{Writing individual scanlines, tiles, and rectangles}
110\label{sec:imageoutput:scanlinestiles}
111
112The simple example of Section~\ref{sec:imageoutput:simple} wrote an
113entire image with one call.  But sometimes you are generating output a
114little at a time and do not wish to retain the entire image in memory
115until it is time to write the file.  \product allows you to write images
116one scanline at a time, one tile at a time, or by individual rectangles.
117
118\subsubsection{Writing individual scanlines}
119
120Individual scanlines may be written using the \writescanline API
121call:
122
123\begin{code}
124        ...
125        unsigned char scanline[xres*channels];
126        out->open (filename, spec);
127        int z = 0;   // Always zero for 2D images
128        for (int y = 0;  y < yres;  ++y) {
129            ... generate data in scanline[0..xres*channels-1] ...
130            out->write_scanline (y, z, TypeDesc::UINT8, scanline);
131        }
132        out->close ();
133        ...
134\end{code}
135
136The first two arguments to \writescanline specify which scanline is
137being written by its vertical ($y$) scanline number (beginning with 0)
138and, for volume images, its slice ($z$) number (the slice number should
139be 0 for 2D non-volume images).  This is followed by a \TypeDesc
140describing the data you are supplying, and a pointer to the pixel data
141itself.  Additional optional arguments describe the data stride, which
142can be ignored for contiguous data (use of strides is explained in
143Section~\ref{sec:imageoutput:strides}).
144
145All \ImageOutput implementations will accept scanlines in strict order
146(starting with scanline 0, then 1, up to {\kw yres-1}, without skipping
147any).  See Section~\ref{sec:imageoutput:randomrewrite} for details
148on out-of-order or repeated scanlines.
149
150The full description of the \writescanline function may be found
151in Section~\ref{sec:imageoutput:reference}.
152
153\subsubsection{Writing individual tiles}
154
155Not all image formats (and therefore not all \ImageOutput
156implementations) support tiled images.  If the format does not support
157tiles, then \writetile will fail.  An application using \product
158should gracefully handle the case that tiled output is not available for
159the chosen format.
160
161Once you {\kw create()} an \ImageOutput, you can ask if it is capable
162of writing a tiled image by using the {\kw supports("tiles")} query:
163
164\begin{code}
165        ...
166        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
167        if (! out->supports ("tiles")) {
168            // Tiles are not supported
169        }
170\end{code}
171
172Assuming that the \ImageOutput supports tiled images, you need to
173specifically request a tiled image when you {\kw open()} the file.  This
174is done by setting the tile size in the \ImageSpec passed
175to {\kw open()}.  If the tile dimensions are not set, they will default
176to zero, which indicates that scanline output should be used rather than
177tiled output.
178
179\begin{code}
180        int tilesize = 64;
181        ImageSpec spec (xres, yres, channels, TypeDesc::UINT8);
182        spec.tile_width = tilesize;
183        spec.tile_height = tilesize;
184        out->open (filename, spec);
185        ...
186\end{code}
187
188In this example, we have used square tiles (the same number of pixels
189horizontally and vertically), but this is not a requirement of \product.
190However, it is possible that some image formats may only support square
191tiles, or only certain tile sizes (such as restricting tile sizes to
192powers of two).  Such restrictions should be documented by each
193individual plugin.
194
195\begin{code}
196        unsigned char tile[tilesize*tilesize*channels];
197        int z = 0;   // Always zero for 2D images
198        for (int y = 0;  y < yres;  y += tilesize) {
199            for (int x = 0;  x < xres;  x += tilesize) {
200                ... generate data in tile[] ..
201                out->write_tile (x, y, z, TypeDesc::UINT8, tile);
202            }
203        }
204        out->close ();
205        ...
206\end{code}
207
208The first three arguments to \writetile specify which tile is
209being written by the pixel coordinates of any pixel contained in the
210tile: $x$ (column), $y$ (scanline), and $z$ (slice, which should always
211be 0 for 2D non-volume images).  This is followed by a \TypeDesc
212describing the data you are supplying, and a pointer to the tile's pixel
213data itself, which should be ordered by increasing slice, increasing
214scanline within each slice, and increasing column within each scanline.
215Additional optional arguments describe the data stride, which can be
216ignored for contiguous data (use of strides is explained in
217Section~\ref{sec:imageoutput:strides}).
218
219All \ImageOutput implementations that support tiles will accept tiles in
220strict order of increasing $y$ rows, and within each row, increasing $x$
221column, without missing any tiles.  See
222Section~\ref{sec:imageoutput:randomrewrite} for details on out-of-order
223or repeated tiles.
224
225The full description of the \writetile function may be found
226in Section~\ref{sec:imageoutput:reference}.
227
228\subsubsection{Writing arbitrary rectangles}
229
230Some \ImageOutput implementations --- such as those implementing an
231interactive image display, but probably not any that are outputting
232directly to a file --- may allow you to send arbitrary rectangular pixel
233regions.  Once you {\kw create()} an \ImageOutput, you can ask if it is
234capable of accepting arbitrary rectangles by using the {\kw
235supports("rectangles")} query:
236
237\begin{code}
238        ...
239        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
240        if (! out->supports ("rectangles")) {
241            // Rectangles are not supported
242        }
243\end{code}
244
245If rectangular regions are supported, they may be sent using
246the {\kw write_rectangle()} API call:
247
248\begin{code}
249        unsigned int rect[...];
250        ... generate data in rect[] ..
251        out->write_rectangle (xbegin, xend, ybegin, yend, zbegin, zend,
252                              TypeDesc::UINT8, rect);
253\end{code}
254
255The first six arguments to {\kw write_rectangle()} specify the region of
256pixels that is being transmitted by supplying the minimum and one-past-maximum
257pixel indices in $x$ (column), $y$ (scanline), and $z$ (slice, always 0
258for 2D non-volume images).\footnote{\OpenImageIO nearly always follows
259the C++ STL convention of specifying ranges as {\cf [begin,end)}, that
260is, {\cf begin, begin+1, ..., end-1.}}
261The total number of pixels being transmitted is therefore:
262\begin{code}
263        (xend-xbegin) * (yend-ybegin) * (zend-zbegin)
264\end{code}
265\noindent This is followed by a \TypeDesc describing the data you
266are supplying, and a pointer to the rectangle's pixel data itself, which
267should be ordered by increasing slice, increasing scanline within each
268slice, and increasing column within each scanline.  Additional optional
269arguments describe the data stride, which can be ignored for contiguous
270data (use of strides is explained in
271Section~\ref{sec:imageoutput:strides}).
272
273
274\subsection{Converting pixel data types}
275\label{sec:imageoutput:convertingtypes}
276
277The code examples of the previous sections all assumed that your
278internal pixel data is stored as unsigned 8-bit integers (i.e., 0-255
279range).  But \product is significantly more flexible.
280
281You may request that the output image pixels be stored in any of several
282data types.  This is done by setting the {\kw format} field of the
283\ImageSpec prior to calling {\kw open}.  You can do this upon
284construction of the \ImageSpec, as in the following example
285that requests a spec that stores pixel values as 16-bit unsigned integers:
286\begin{code}
287        ImageSpec spec (xres, yres, channels, TypeDesc::UINT16);
288\end{code}
289
290\noindent Or, for an \ImageSpec that has already been
291constructed, you may reset its format using the {\kw set_format()}
292method.
293
294\begin{code}
295        ImageSpec spec (...);
296        spec.set_format (TypeDesc::UINT16);
297\end{code}
298
299Note that resetting the pixel data type must be done \emph{before} passing
300the spec to {\kw open()}, or it will have no effect on the file.
301
302Individual file formats, and therefore \ImageOutput implementations, may
303only support a subset of the pixel data types understood by the \product library.
304Each \ImageOutput plugin implementation should document which data
305formats it supports.  An individual \ImageOutput implementation is expected
306to always succeed, but if the file format does not support the requested
307pixel data type, it is expected to choose a data type that is supported,
308usually the data type that best preserves the precision and range
309of the originally-requested data type.
310
311
312The conversion from floating-point formats to integer formats (or from
313higher to lower integer, which is done by first converting to float) is
314always done by rescaling the value so that $0.0$ maps to integer $0$ and
315$1.0$ to the maximum value representable by the integer type, then rounded
316to an integer value for final output.  Here is the code that implements this
317transformation ({\cf T} is the final output integer type):
318
319\begin{code}
320        float value = quant_max * input;
321        T output = (T) clamp ((int)(value + 0.5), quant_min, quant_max);
322\end{code}
323
324\noindent Quantization limits for each integer type is as follows:\\
325
326\smallskip
327\begin{tabular}{|l|r|r|}
328\hline
329{\bf Data Format} & {\bf min} & {\bf max} \\
330\hline
331{\cf UINT8}  &           0 &        255 \\
332{\cf INT8}   &        -128 &        127 \\
333{\cf UINT16} &           0 &      65535 \\
334{\cf INT16}  &      -32768 &      32767 \\
335{\cf UINT}   &           0 & 4294967295 \\
336{\cf INT}    & -2147483648 & 2147483647 \\
337\hline
338\end{tabular} \\
339\smallskip
340
341\noindent Note that the default is to use the entire positive range
342of each integer type to represent the floating-point ($0.0 - 1.0$) range.
343Floating-point types do not attempt to remap values,
344and do not clamp (except to their full floating-point range).
345
346
347It is not required that the pixel data passed to \writeimage,
348\writescanline, \writetile, or {\kw write_rectangle()} actually be in
349the same data type as that requested as the native pixel data type of the file.
350You can fully mix and match data you pass to the various {\kw write}
351routines and \product will automatically convert from the internal
352format to the native file format.  For example, the following code will
353open a TIFF file that stores pixel data as 16-bit unsigned integers
354(values ranging from 0 to 65535), compute internal pixel values as
355floating-point values, with \writeimage performing the conversion
356automatically:
357
358\begin{code}
359        std::unique_ptr<ImageOutput> out = ImageOutput::create ("myfile.tif");
360        ImageSpec spec (xres, yres, channels, TypeDesc::UINT16);
361        out->open (filename, spec);
362        ...
363        float pixels [xres*yres*channels];
364        ...
365        out->write_image (TypeDesc::FLOAT, pixels);
366\end{code}
367
368\noindent Note that \writescanline, \writetile, and {\cf
369  write_rectangle} have a parameter that works in a corresponding
370manner.
371
372
373\subsection{Data Strides}
374\label{sec:imageoutput:strides}
375
376In the preceeding examples, we have assumed that the block of data being
377passed to the {\cf write} functions are \emph{contiguous}, that is:
378
379\begin{itemize}
380\item each pixel in memory consists of a number of data values equal to
381  the declared number of channels that are being written to the file;
382\item successive column pixels within a row directly follow each other in
383  memory, with the first channel of pixel $x$ immediately following
384  last channel of pixel $x-1$ of the same row;
385\item for whole images, tiles or rectangles, the data for each row
386  immediately follows the previous one in memory (the first pixel of row
387  $y$ immediately follows the last column of row $y-1$);
388\item for 3D volumetric images, the first pixel of slice $z$ immediately
389  follows the last pixel of of slice $z-1$.
390\end{itemize}
391
392Please note that this implies that data passed to
393\writetile be contiguous in the shape of a single tile (not just an
394offset into a whole image worth of pixels), and that data passed to {\cf
395  write_rectangle()} be contiguous in the dimensions of the rectangle.
396
397The \writescanline function takes an optional {\cf xstride} argument,
398and the \writeimage, \writetile, and {\cf write_rectangle} functions
399take optional {\cf xstride}, {\cf ystride}, and {\cf zstride} values
400that describe the distance, in \emph{bytes}, between successive pixel
401columns, rows, and slices, respectively, of the data you are passing.
402For any of these values that are not supplied, or are given as the
403special constant {\cf AutoStride}, contiguity will be assumed.
404
405By passing different stride values, you can achieve some surprisingly
406flexible functionality.  A few representative examples follow:
407
408\begin{itemize}
409\item Flip an image vertically upon writing, by using \emph{negative}
410  $y$ stride:
411  \begin{code}
412    unsigned char pixels[xres*yres*channels];
413    int scanlinesize = xres * channels * sizeof(pixels[0]);
414    ...
415    out->write_image (TypeDesc::UINT8,
416                      (char *)pixels+(yres-1)*scanlinesize, // offset to last
417                      AutoStride,                  // default x stride
418                      -scanlinesize,               // special y stride
419                      AutoStride);                 // default z stride
420  \end{code}
421\item Write a tile that is embedded within a whole image of pixel data,
422  rather than having a one-tile-only memory layout:
423  \begin{code}
424    unsigned char pixels[xres*yres*channels];
425    int pixelsize = channels * sizeof(pixels[0]);
426    int scanlinesize = xres * pixelsize;
427    ...
428    out->write_tile (x, y, 0, TypeDesc::UINT8,
429                     (char *)pixels + y*scanlinesize + x*pixelsize,
430                     pixelsize,
431                     scanlinesize);
432  \end{code}
433\item Write only a subset of channels to disk.  In this example, our
434  internal data layout consists of 4 channels, but we write just
435  channel 3 to disk as a one-channel image:
436  \begin{code}
437    // In-memory representation is 4 channel
438    const int xres = 640, yres = 480;
439    const int channels = 4;  // RGBA
440    const int channelsize = sizeof(unsigned char);
441    unsigned char pixels[xres*yres*channels];
442
443    // File representation is 1 channel
444    std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
445    ImageSpec spec (xres, yres, 1, TypeDesc::UINT8);
446    out->open (filename, spec);
447
448    // Use strides to write out a one-channel "slice" of the image
449    out->write_image (TypeDesc::UINT8,
450                      (char *)pixels+3*channelsize, // offset to chan 3
451                      channels*channelsize,         // 4 channel x stride
452                      AutoStride,                   // default y stride
453                      AutoStride);                  // default z stride
454    ...
455  \end{code}
456\end{itemize}
457
458Please consult Section~\ref{sec:imageoutput:reference} for detailed
459descriptions of the stride parameters to each {\cf write} function.
460
461
462\subsection{Writing a crop window or overscan region}
463\label{sec:imageoutput:cropwindows}
464\index{crop windows} \index{overscan}
465
466% FIXME -- Marcos suggests adding a figure here to illustrate
467% the w/h/d, xyz, full
468
469The \ImageSpec fields {\cf width}, {\cf height}, and {\cf depth}
470describe the dimensions of the actual pixel data.
471
472At times, it may be useful to also describe an abstract \emph{full} or
473\emph{display} image window, whose position and size may not correspond
474exactly to the data pixels.  For example, a pixel data window that is a
475subset of the full display window might indicate a \emph{crop window}; a
476pixel data window that is a superset of the full display window might
477indicate \emph{overscan} regions (pixels defined outside the eventual
478viewport).
479
480The \ImageSpec fields {\cf full_width}, {\cf full_height}, and
481{\cf full_depth} describe the dimensions of the full display
482window, and {\cf full_x}, {\cf full_y}, {\cf full_z} describe its
483origin (upper left corner).  The fields {\cf x}, {\cf y}, {\cf z}
484describe the origin (upper left corner)
485of the pixel data.
486
487These fields collectively describe an abstract full display image
488ranging from [{\cf full_x} ... {\cf full_x+full_width-1}] horizontally,
489[{\cf full_y} ... {\cf full_y+full_height-1}] vertically,
490and [{\cf full_z} ... {\cf full_z+full_depth-1}] in depth (if it is
491a 3D volume), and actual pixel data over the pixel coordinate range
492[{\cf x} ... {\cf x+width-1}] horizontally,
493[{\cf y} ... {\cf y+height-1}] vertically,
494and [{\cf z} ... {\cf z+depth-1}] in depth (if it is a volume).
495
496Not all image file formats have a way to describe display windows.  An
497\ImageOutput implementation that cannot express display windows will
498always write out the {\cf width} $\times$ {\cf height} pixel data, may
499upon writing lose information about offsets or crop windows.
500
501Here is a code example that opens an image file that will contain a $32
502\times 32$ pixel crop window within an abstract $640 \times 480$ full
503size image.  Notice that the pixel indices (column, scanline, slice)
504passed to the {\cf write} functions are the coordinates relative to
505the full image, not relative to the crop widow, but the data pointer
506passed to the {\cf write} functions should point to the beginning of
507the actual pixel data being passed (not the the hypothetical start of
508the full data, if it was all present).
509
510\begin{code}
511        int fullwidth = 640, fulllength = 480; // Full display image size
512        int cropwidth = 16, croplength = 16;  // Crop window size
513        int xorigin = 32, yorigin = 128;      // Crop window position
514        unsigned char pixels [cropwidth * croplength * channels]; // Crop size!
515        ...
516        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
517        ImageSpec spec (cropwidth, croplength, channels, TypeDesc::UINT8);
518        spec.full_x = 0;
519        spec.full_y = 0;
520        spec.full_width = fullwidth;
521        spec.full_length = fulllength;
522        spec.x = xorigin;
523        spec.y = yorigin;
524        out->open (filename, spec);
525        ...
526        int z = 0;   // Always zero for 2D images
527        for (int y = yorigin;  y < yorigin+croplength;  ++y) {
528            out->write_scanline (y, z, TypeDesc::UINT8,
529                                 (y-yorigin)*cropwidth*channels);
530        }
531        out->close ();
532\end{code}
533
534
535\subsection{Writing metadata}
536\label{sec:imageoutput:metadata}
537
538The \ImageSpec passed to {\cf open()} can specify all the common
539required properties that describe an image: data format, dimensions,
540number of channels, tiling.  However, there may be a variety of
541additional \emph{metadata}\footnote{\emph{Metadata} refers to data about
542data, in this case, data about the image that goes beyond the pixel
543values and description thereof.} that should be carried along with the
544image or saved in the file.
545
546The remainder of this section explains how to store additional metadata
547in the \ImageSpec.  It is up to the \ImageOutput to store these
548in the file, if indeed the file format is able to accept the data.
549Individual \ImageOutput implementations should document which metadata
550they respect.
551
552\subsubsection{Channel names}
553
554In addition to specifying the number of color channels, it is also
555possible to name those channels.  Only a few \ImageOutput
556implementations have a way of saving this in the file, but some do, so
557you may as well do it if you have information about what the channels
558represent.
559
560By convention, channel names for red, green, blue, and alpha (or a main
561image) should be named \qkw{R}, \qkw{G}, \qkw{B}, and \qkw{A},
562respectively.  Beyond this guideline, however, you can use any names you
563want.
564
565The \ImageSpec has a vector of strings called {\cf
566  channelnames}.  Upon construction, it starts out with reasonable
567default values.  If you use it
568at all, you should make sure that it contains the same number of strings
569as the number of color channels in your image.  Here is an example:
570
571\begin{code}
572        int channels = 4;
573        ImageSpec spec (width, length, channels, TypeDesc::UINT8);
574        spec.channelnames.clear ();
575        spec.channelnames.push_back ("R");
576        spec.channelnames.push_back ("G");
577        spec.channelnames.push_back ("B");
578        spec.channelnames.push_back ("A");
579\end{code}
580
581Here is another example in which custom channel names are used to
582label the channels in an 8-channel image containing beauty pass
583RGB, per-channel opacity, and texture $s,t$ coordinates for each pixel.
584
585\begin{code}
586        int channels = 8;
587        ImageSpec spec (width, length, channels, TypeDesc::UINT8);
588        spec.channelnames.clear ();
589        spec.channelnames.push_back ("R");
590        spec.channelnames.push_back ("G");
591        spec.channelnames.push_back ("B");
592        spec.channelnames.push_back ("opacityR");
593        spec.channelnames.push_back ("opacityG");
594        spec.channelnames.push_back ("opacityB");
595        spec.channelnames.push_back ("texture_s");
596        spec.channelnames.push_back ("texture_t");
597\end{code}
598
599The main advantage to naming color channels is that if you are saving to
600a file format that supports channel names, then any application that
601uses \product to read the image back has the option to retain those
602names and use them for helpful purposes.  For example, the {\cf iv}
603image viewer will display the channel names when viewing individual
604channels or displaying numeric pixel values in ``pixel view'' mode.
605
606
607\subsubsection{Specially-designated channels}
608
609The \ImageSpec contains two fields, {\cf alpha_channel} and {\cf
610  z_channel}, which can be used to designate which channel indices are
611used for alpha and $z$ depth, if any.  Upon construction, these are both
612set to {\cf -1}, indicating that it is not known which channels
613are alpha or depth.  Here is an example of setting up a 5-channel output
614that represents RGBAZ:
615
616\begin{code}
617        int channels = 5;
618        ImageSpec spec (width, length, channels, format);
619        spec.channelnames.push_back ("R");
620        spec.channelnames.push_back ("G");
621        spec.channelnames.push_back ("B");
622        spec.channelnames.push_back ("A");
623        spec.channelnames.push_back ("Z");
624        spec.alpha_channel = 3;
625        spec.z_channel = 4;
626\end{code}
627
628There are two advantages to designating the alpha and depth channels in
629this manner:
630\begin{itemize}
631\item Some file formats may require that these channels be stored in a
632  particular order, with a particular precision, or the \ImageOutput may
633  in some other way need to know about these special channels.
634\end{itemize}
635
636\subsubsection{Arbitrary metadata}
637
638For all other metadata that you wish to save in the file, you can attach
639the data to the \ImageSpec using the {\cf attribute()} methods.
640These come in polymorphic varieties that allow you to attach an
641attribute name and a value consisting of a single {\cf int}, {\cf
642  unsigned int}, {\cf float}, {\cf char*}, or {\cf std::string}, as
643shown in the following examples:
644
645\begin{code}
646        ImageSpec spec (...);
647        ...
648
649        unsigned int u = 1;
650        spec.attribute ("Orientation", u);
651
652        float x = 72.0;
653        spec.attribute ("dotsize", f);
654
655        std::string s = "Fabulous image writer 1.0";
656        spec.attribute ("Software", s);
657\end{code}
658
659These are convenience routines for metadata that consist of a single
660value of one of these common types.  For other data types, or more
661complex arrangements, you can use the more general form of {\cf
662  attribute()}, which takes arguments giving the name, type (as a
663\TypeDesc), number of values (1 for a single value, $>1$ for an
664  array), and then a pointer to the data values.  For example,
665
666\begin{code}
667        ImageSpec spec (...);
668
669        // Attach a 4x4 matrix to describe the camera coordinates
670        float mymatrix[16] = { ... };
671        spec.attribute ("worldtocamera", TypeMatrix, &mymatrix);
672
673        // Attach an array of two floats giving the CIE neutral color
674        float neutral[2] = { ... };
675        spec.attribute ("adoptedNeutral", TypeDesc(TypeDesc::FLOAT, 2), &neutral);
676\end{code}
677
678In general, most image file formats (and therefore most \ImageOutput
679implementations) are aware of only a small number of name/value pairs
680that they predefine and will recognize.  Some file formats (OpenEXR,
681notably) do accept arbitrary user data and save it in the image file.
682If an \ImageOutput does not recognize your metadata and does not support
683arbitrary metadata, that metadatum will be silently ignored and will not
684be saved with the file.
685
686Each individual \ImageOutput implementation should document the names,
687types, and meanings of all metadata attributes that they understand.
688
689
690\subsubsection{Color space hints}
691
692We certainly hope that you are using only modern file formats that
693support high precision and extended range pixels (such as OpenEXR) and
694keeping all your images in a linear color space.  But you may have to
695work with file formats that dictate the use of nonlinear color values.
696This is prevalent in formats that store pixels only as 8-bit values,
697since 256 values are not enough to linearly represent colors without
698banding artifacts in the dim values.
699
700Since this can (and probably will) happen, we have a convention
701for explaining what color space your image pixels are
702in.  Each individual \ImageOutput should document how it uses this (or
703not).
704
705The {\cf ImageSpec::extra_attribs} field should store metadata that
706reveals the color space of the pixels you are sending the ImageOutput
707(see Section~\ref{metadata:colorspace} for explanations of
708particular values).
709
710\noindent The color space hints only describe color channels.  You should always
711pass alpha, depth, or other non-color channels with linear values.
712
713Here is a simple example of setting up the \ImageSpec
714when you know that the pixel values you are writing are linear:
715
716\begin{code}
717        ImageSpec spec (width, length, channels, format);
718        spec.attribute ("oiio:ColorSpace", "Linear");
719        ...
720\end{code}
721
722If a particular \ImageOutput implementation is required (by the rules of
723the file format it writes) to have pixels in a particular color space,
724then it should try to convert the color values of your image to the right color
725space if it is not already in that space.  For example, JPEG images
726must be in sRGB space, so if you declare your pixels to be \qkw{Linear},
727the JPEG \ImageOutput will convert to sRGB.
728
729If you leave the \qkw{oiio:ColorSpace} unset, the values will not be
730transformed, since the plugin can't be sure that it's not in the correct
731space to begin with.
732
733
734
735\subsection{Random access and repeated transmission of pixels}
736\label{sec:imageoutput:randomrewrite}
737
738All \ImageOutput implementations that support scanlines and tiles should write pixels in strict
739order of increasing $z$ slice, increasing $y$ scanlines/rows within each
740slice, and increasing $x$ column within each row.  It is generally not
741safe to skip scanlines or tiles, or transmit them out of order, unless
742the plugin specifically advertises that it supports random access or
743rewrites, which may be queried using:
744
745\begin{code}
746        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
747        if (out->supports ("random_access"))
748            ...
749\end{code}
750
751\noindent Similarly, you should assume the plugin will not correctly
752handle repeated transmissions of a scanline or tile that has already
753been sent, unless it advertises that it supports rewrites, which may be
754queried using:
755
756\begin{code}
757        if (out->supports ("rewrite"))
758            ...
759\end{code}
760
761
762\subsection{Multi-image files}
763\label{sec:imageoutput:multiimage}
764
765Some image file formats support storing multiple images within a single
766file.  Given a created \ImageOutput, you can query whether multiple
767images may be stored in the file:
768
769\begin{code}
770        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
771        if (out->supports ("multiimage"))
772            ...
773\end{code}
774
775Some image formats allow you to do the initial {\cf open()} call
776without declaring the specifics of the subimages, and simply append
777subimages as you go.  You can detect this by checking
778\begin{code}
779        if (out->supports ("appendsubimage"))
780            ...
781\end{code}
782
783In this case, all you have to do is, after writing all the pixels of one
784image but before calling {\cf close()}, call {\cf open()} again for the
785next subimage and pass {\cf AppendSubimage} as the value for the
786\emph{mode} argument (see Section~\ref{sec:imageoutput:reference} for
787the full technical description of the arguments to {\cf open}).  The
788{\cf close()} routine is called just once, after all subimages are
789completed.  Here is an example:
790
791\begin{code}
792        const char *filename = "foo.tif";
793        int nsubimages;     // assume this is set
794        ImageSpec specs[];  // assume these are set for each subimage
795        unsigned char *pixels[]; // assume a buffer for each subimage
796
797        // Create the ImageOutput
798        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
799
800        // Be sure we can support subimages
801        if (subimages > 1 &&  (! out->supports("multiimage") ||
802                               ! out->supports("appendsubimage"))) {
803            std::cerr << "Does not support appending of subimages\n";
804            return;
805        }
806
807        // Use Create mode for the first level.
808        ImageOutput::OpenMode appendmode = ImageOutput::Create;
809
810        // Write the individual subimages
811        for (int s = 0;  s < nsubimages;  ++s) {
812            out->open (filename, specs[s], appendmode);
813            out->write_image (TypeDesc::UINT8, pixels[s]);
814            // Use AppendSubimage mode for subsequent levels
815            appendmode = ImageOutput::AppendSubimage;
816        }
817        out->close ();
818\end{code}
819
820
821On the other hand, if {\cf out->supports("appendsubimage")} returns
822{\cf false}, then you must use a different {\cf open()} variety that
823allows you to declare the number of subimages and their specifications
824up front.
825
826Below is an example of how to write a multi-subimage file, assuming that
827you know all the image specifications ahead of time.  This should be
828safe for any file format that supports multiple subimages, regardless of
829whether it supports appending, and thus is the preferred method for
830writing subimages, assuming that you are able to know the number and
831specification of the subimages at the time you first open the file.
832
833\begin{code}
834        const char *filename = "foo.tif";
835        int nsubimages;     // assume this is set
836        ImageSpec specs[];  // assume these are set for each subimage
837        unsigned char *pixels[]; // assume a buffer for each subimage
838
839        // Create the ImageOutput
840        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
841
842        // Be sure we can support subimages
843        if (subimages > 1 && ! out->supports ("multiimage")) {
844            std::cerr << "Cannot write multiple subimages\n";
845            return;
846        }
847
848        // Open and declare all subimages
849        out->open (filename, nsubimages, specs);
850
851        // Write the individual subimages
852        for (int s = 0;  s < nsubimages;  ++s) {
853            if (s > 0)  // Not needed for the first, which is already open
854                out->open (filename, specs[s], ImageInput::AppendSubimage);
855            out->write_image (TypeDesc::UINT8, pixels[s]);
856        }
857        out->close ();
858\end{code}
859
860In both of these examples, we have used \writeimage, but of course
861\writescanline, \writetile, and {\cf write_rectangle()} work as you
862would expect, on the current subimage.
863
864
865\subsection{MIP-maps}
866\label{sec:imageoutput:mipmap}
867
868Some image file formats support multiple copies of an image at successively
869lower resolutions (MIP-map levels, or an ``image pyramid'').  Given a
870created \ImageOutput, you can query whether MIP-maps may be
871stored in the file:
872
873\begin{code}
874        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
875        if (out->supports ("mipmap"))
876            ...
877\end{code}
878
879If you are working with an \ImageOutput that supports MIP-map levels, it
880is easy to write these levels.  After writing all the pixels of one
881MIP-map level,
882call {\cf open()} again for the next MIP level and pass
883{\cf ImageInput::AppendMIPLevel} as the value for the \emph{mode}
884argument, and then write the pixels of the subsequent MIP level.
885(See Section~\ref{sec:imageoutput:reference} for
886the full technical description of the arguments to {\cf open()}.)  The
887{\cf close()} routine is called just once, after all subimages and MIP
888levels are completed.
889
890Below is pseudocode for writing a MIP-map (a multi-resolution image
891used for texture mapping):
892
893\begin{code}
894        const char *filename = "foo.tif";
895        const int xres = 512, yres = 512;
896        const int channels = 3;  // RGB
897        unsigned char *pixels = new unsigned char [xres*yres*channels];
898
899        // Create the ImageOutput
900        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
901
902        // Be sure we can support either mipmaps or subimages
903        if (! out->supports ("mipmap") && ! out->supports ("multiimage")) {
904            std::cerr << "Cannot write a MIP-map\n";
905            return;
906        }
907        // Set up spec for the highest resolution
908        ImageSpec spec (xres, yres, channels, TypeDesc::UINT8);
909
910        // Use Create mode for the first level.
911        ImageOutput::OpenMode appendmode = ImageOutput::Create;
912
913        // Write images, halving every time, until we're down to
914        // 1 pixel in either dimension
915        while (spec.width >= 1 && spec.height >= 1) {
916            out->open (filename, spec, appendmode);
917            out->write_image (TypeDesc::UINT8, pixels);
918            // Assume halve() resamples the image to half resolution
919            halve (pixels, spec.width, spec.height);
920            // Don't forget to change spec for the next iteration
921            spec.width /= 2;
922            spec.height /= 2;
923
924            // For subsequent levels, change the mode argument to
925            // open().  If the format doesn't support MIPmaps directly,
926            // try to emulate it with subimages.
927            if (out->supports("mipmap"))
928                appendmode = ImageOutput::AppendMIPLevel;
929            else
930                appendmode = ImageOutput::AppendSubimage;
931        }
932        out->close ();
933\end{code}
934
935In this example, we have used \writeimage, but of course \writescanline,
936\writetile, and {\cf write_rectangle()} work as you would expect, on the
937current MIP level.
938
939
940\subsection{Per-channel formats}
941\label{sec:imageoutput:channelformats}
942
943Some image formats allow separate per-channel data formats (for example,
944{\cf half} data for colors and {\cf float} data for depth).  When this
945is desired, the following steps are necessary:
946
947\begin{enumerate}
948\item Verify that the writer supports per-channel formats by checking \\
949  {\cf supports ("channelformats")}.
950\item The \ImageSpec passed to {\cf open()} should have its {\cf
951  channelformats} vector filled with the types for each channel.
952\item The call to {\cf write_scanline}, {\cf read_scanlines},
953  {\cf write_tile}, {\cf write_tiles}, or {\cf
954  write_image} should pass a {\cf data} pointer to the raw data, already
955  in the native per-channel format of the file and contiguously packed,
956  and specify that the data is of type {\cf TypeDesc::UNKNOWN}.
957\end{enumerate}
958
959For example, the following code fragment will write a 5-channel image
960to an OpenEXR file, consisting of R/G/B/A channels in {\cf half} and
961a Z channel in {\cf float}:
962
963\begin{code}
964        // Mixed data type for the pixel
965        struct Pixel { half r,g,b,a; float z; };
966        Pixel pixels[xres*yres];
967
968        std::unique_ptr<ImageOutput> out = ImageOutput::create ("foo.exr");
969
970        // Double check that this format accepts per-channel formats
971        if (! out->supports("channelformats")) {
972            return;
973        }
974
975        // Prepare an ImageSpec with per-channel formats
976        ImageSpec spec (xres, yres, 5, TypeDesc::FLOAT);
977        spec.channelformats.push_back (TypeDesc::HALF);
978        spec.channelformats.push_back (TypeDesc::HALF);
979        spec.channelformats.push_back (TypeDesc::HALF);
980        spec.channelformats.push_back (TypeDesc::HALF);
981        spec.channelformats.push_back (TypeDesc::FLOAT);
982        spec.channelnames.clear ();
983        spec.channelnames.push_back ("R");
984        spec.channelnames.push_back ("G");
985        spec.channelnames.push_back ("B");
986        spec.channelnames.push_back ("A");
987        spec.channelnames.push_back ("Z");
988
989        out->open (filename, spec);
990        out->write_image (TypeDesc::UNKNOWN, /* use channel formats */
991                          pixels,            /* data buffer */
992                          sizeof(Pixel));    /* pixel stride */
993\end{code}
994
995
996\subsection{Writing ``deep'' data}
997\label{sec:imageoutput:deepdata}  \index{deep data}
998Some image file formats (OpenEXR only, at this time) support the concept
999of ``deep'' pixels -- those containing multiple samples per pixel (and a
1000potentially differing number of them in each pixel).  You can tell
1001if a format supports deep images by checking {\cf supports("deepdata")},
1002and you can specify a deep data in an \ImageSpec by setting its {\cf deep}
1003field will be {\cf true}.
1004
1005Deep files cannot be written with the usual {\cf write_scanline}, {\cf
1006  write_scanlines}, {\cf write_tile}, {\cf write_tiles}, {\cf write_image}
1007functions, due to the nature of their variable number of samples per
1008pixel.  Instead, \ImageOutput has three special member functions used
1009only for writing deep data:
1010
1011\begin{code}
1012    bool write_deep_scanlines (int ybegin, int yend, int z,
1013                               const DeepData &deepdata);
1014
1015    bool write_deep_tiles (int xbegin, int xend, int ybegin, int yend,
1016                           int zbegin, int zend, const DeepData &deepdata);
1017
1018    bool write_deep_image (const DeepData &deepdata);
1019\end{code}
1020
1021It is only possible to write ``native'' data types to deep files; that
1022is, there is no automatic translation into arbitrary data types as there
1023is for ordinary images.  All three of these functions are passed
1024deep data in a special {\cf DeepData} structure, described in
1025detail in Section~\ref{sec:deepdata}.
1026
1027
1028\noindent Here is an example of using these methods to write a deep image:
1029
1030\begin{code}
1031    // Prepare the spec for 'half' RGBA, 'float' z
1032    int nchannels = 5;
1033    ImageSpec spec (xres, yres, nchannels);
1034    TypeDesc channeltypes[] = { TypeDesc::HALF, TypeDesc::HALF,
1035          TypeDesc::HALF, TypeDesc::HALF, TypeDesc::FLOAT };
1036    spec.z_channel = 4;
1037    spec.channelnames[spec.z_channel] = "Z";
1038    spec.channeltypes.assign (channeltypes+0, channeltypes+nchannels);
1039    spec.deep = true;
1040
1041    // Prepare the data (sorry, complicated, but need to show the gist)
1042    DeepData deepdata;
1043    deepdata.init (spec);
1044    for (int y = 0;  y < yres;  ++y)
1045        for (int x = 0;  x < xres;  ++x)
1046            deepdata.set_samples(y*xres+x, ...samples for that pixel...);
1047    deepdata.alloc ();  // allocate pointers and data
1048    int pixel = 0;
1049    for (int y = 0;  y < yres;  ++y)
1050        for (int x = 0;  x < xres;  ++x, ++pixel)
1051            for (int chan = 0;  chan < nchannels;  ++chan)
1052                for (int samp = 0; samp < deepdata.samples(pixel); ++samp)
1053                    deepdata.set_deep_value (pixel, chan, samp, ...value...);
1054
1055
1056    // Create the output
1057    std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
1058    if (! out)
1059        return;
1060    // Make sure the format can handle deep data and per-channel formats
1061    if (! out->supports("deepdata") || ! out->supports("channelformats"))
1062        return;
1063
1064    // Do the I/O (this is the easy part!)
1065    out->open (filename, spec);
1066    out->write_deep_image (deepdata);
1067    out->close ();
1068\end{code}
1069
1070
1071\subsection{Copying an entire image}
1072\label{sec:imageoutput:copyimage}
1073
1074Suppose you want to copy an image, perhaps with alterations to the
1075metadata but not to the pixels.  You could open an \ImageInput and
1076perform a {\cf read_image()}, and open another \ImageOutput and
1077call {\cf write_image()} to output the pixels from the input image.
1078However, for compressed images, this may be inefficient due to the
1079unnecessary decompression and subsequent re-compression.  In addition,
1080if the compression is \emph{lossy}, the output image may not contain
1081pixel values identical to the original input.
1082
1083A special {\cf copy_image} method of \ImageOutput is available that
1084attempts to copy an image from an open \ImageInput (of the same
1085format) to the output as efficiently as possible with without altering
1086pixel values, if at all possible.
1087
1088Not all format plugins will provide an implementation of {\cf
1089  copy_image} (in fact, most will not), but the default implemenatation
1090simply copies pixels one scanline or tile at a time (with
1091decompression/recompression) so it's still safe to call.  Furthermore,
1092even a provided {\cf copy_image} is expected to fall back on the default
1093implementation if the input and output are not able to do an efficient
1094copy.  Nevertheless, this method is recommended
1095for copying images so that maximal advantage will be taken in cases
1096where savings can be had.
1097
1098The following is an example use of {\cf copy_image} to transfer pixels
1099without alteration while modifying the image description metadata:
1100
1101\begin{code}
1102    // Open the input file
1103    const char *input = "input.jpg";
1104    std::unique_ptr<ImageInput> in = ImageInput::open (input);
1105
1106    // Make an output spec, identical to the input except for metadata
1107    ImageSpec out_spec = in->spec();
1108    out_spec.attribute ("ImageDescription", "My Title");
1109
1110    // Create the output file and copy the image
1111    const char *output = "output.jpg";
1112    std::unique_ptr<ImageOutput> out = ImageOutput::create (output);
1113    out->open (output, out_spec);
1114    out->copy_image (in);
1115
1116    // Clean up
1117    out->close ();
1118    in->close ();
1119\end{code}
1120
1121
1122\subsection{Custom I/O proxies (and writing the file to a memory buffer)}
1123\label{sec:imageoutput:ioproxy}
1124\index{writing an image file to memory buffer}
1125
1126Some file format writers allow you to supply a custom I/O proxy object that
1127can allow bypassing the usual file I/O with custom behavior, including the
1128ability to fill an in-memory buffer with a byte-for-byte representation of
1129the correctly formatted file that would have been written to disk.
1130
1131Only some output format writers support this feature. To find out if a
1132particular file format supports this feature, you can create an \ImageOutput
1133of the right type, and check if it supports the feature name \qkw{ioproxy}:
1134
1135\begin{code}
1136    ImageOutput *out = ImageOutput::create (filename);
1137    if (! out  ||  ! out->supports ("ioproxy")) {
1138        ImageOutput::destroy (out);
1139        out = nullptr;
1140        return;
1141    }
1142\end{code}
1143
1144\ImageOutput writers that support \qkw{ioproxy} will respond to a special
1145attribute, \qkw{oiio:ioproxy}, which passes a pointer to a {\cf
1146Filesystem::IOProxy*} (see \product's {\cf filesystem.h} for this type and
1147its subclasses). {\cf IOProxy} is an abstract type, and concrete subclasses
1148include {\cf IOFile} (which wraps I/O to an open {\cf FILE*}) and {\cf
1149IOVecOutput} (which sends output to a {\cf std::vector<unsigned char>}).
1150
1151Here is an example of using a proxy that writes the ``file'' to a
1152{\cf std::vector<unsigned char>}:
1153
1154\begin{code}
1155    // ImageSpec describing the image we want to write.
1156    ImageSpec spec (xres, yres, channels, TypeDesc::UINT8);
1157
1158    std::vector<unsigned char> file_buffer;  // bytes will go here
1159    Filesystem::IOVecOutput vecout (file_buffer);  // I/O proxy object
1160    void *ptr = &vecout;
1161    spec.attribute ("oiio:ioproxy", TypeDesc::PTR, &ptr);
1162
1163    ImageOutput *out = ImageOutput::open ("out.exr", spec);
1164    out->write_image (...);
1165    ImageOutput::destroy (out);
1166
1167    // At this point, file_buffer will contain the "file"
1168\end{code}
1169
1170
1171
1172\subsection{Custom search paths for plugins}
1173\label{sec:imageoutput:searchpaths}
1174
1175When you call {\cf ImageOutput::create()}, the \product library will try
1176to find a plugin that is able to write the format implied by your
1177filename.  These plugins are alternately known as DLL's on Windows (with
1178the {\cf .dll} extension), DSO's on Linux (with the {\cf .so}
1179extension), and dynamic libraries on Mac OS X (with the {\cf .dylib}
1180extension).
1181
1182\product will look for matching plugins according to
1183\emph{search paths}, which are strings giving a list of directories to
1184search, with each directory separated by a colon (`{\cf :}').  Within
1185a search path, any
1186substrings of the form {\cf \$\{FOO\}} will be replaced
1187by the value of environment variable {\cf FOO}.  For
1188example, the searchpath \qkw{\$\{HOME\}/plugins:/shared/plugins}
1189will first check the directory \qkw{/home/tom/plugins} (assuming the
1190user's home directory is {\cf /home/tom}), and if not
1191found there, will then check the directory \qkw{/shared/plugins}.
1192
1193The first search path it will check is that stored in the environment
1194variable {\cf OIIO_LIBRARY_PATH}.  It will check each directory in
1195turn, in the order that they are listed in the variable.  If no adequate
1196plugin is found in any of the directories listed in this environment
1197variable, then it will check the custom searchpath passed as the
1198optional second argument to {\cf ImageOutput::create()}, searching in
1199the order that the directories are listed.  Here is an example:
1200
1201\begin{code}
1202        char *mysearch = "/usr/myapp/lib:${HOME}/plugins";
1203        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename, mysearch);
1204        ...
1205\end{code} % $
1206
1207
1208\subsection{Error checking}
1209\label{sec:imageoutput:errors}
1210\index{error checking}
1211
1212Nearly every \ImageOutput API function returns a {\cf bool} indicating
1213whether the operation succeeded ({\cf true}) or failed ({\cf false}).
1214In the case of a failure, the \ImageOutput will have saved an error
1215message describing in more detail what went wrong, and the latest
1216error message is accessible using the \ImageOutput method
1217{\cf geterror()}, which returns the message as a {\cf std::string}.
1218
1219The exception to this rule is {\cf ImageOutput::create}, which returns
1220{\cf NULL} if it could not create an appropriate \ImageOutput.  And in
1221this case, since no \ImageOutput exists for which you can call its {\cf
1222  geterror()} function, there exists a global {\cf geterror()}
1223function (in the {\cf OpenImageIO} namespace) that retrieves the latest
1224error message resulting from a call to {\cf create}.
1225
1226Here is another version of the simple image writing code from
1227Section~\ref{sec:imageoutput:simple}, but this time it is fully
1228elaborated with error checking and reporting:
1229
1230\begin{code}
1231        #include <OpenImageIO/imageio.h>
1232        using namespace OIIO;
1233        ...
1234
1235        const char *filename = "foo.jpg";
1236        const int xres = 640, yres = 480;
1237        const int channels = 3;  // RGB
1238        unsigned char pixels[xres*yres*channels];
1239
1240        std::unique_ptr<ImageOutput> out = ImageOutput::create (filename);
1241        if (! out) {
1242            std::cerr << "Could not create an ImageOutput for "
1243                      << filename << ", error = "
1244                      << OpenImageIO::geterror() << "\n";
1245            return;
1246        }
1247        ImageSpec spec (xres, yres, channels, TypeDesc::UINT8);
1248
1249        if (! out->open (filename, spec)) {
1250            std::cerr << "Could not open " << filename
1251                      << ", error = " << out->geterror() << "\n";
1252            return;
1253        }
1254
1255        if (! out->write_image (TypeDesc::UINT8, pixels)) {
1256            std::cerr << "Could not write pixels to " << filename
1257                      << ", error = " << out->geterror() << "\n";
1258            return;
1259        }
1260
1261        if (! out->close ()) {
1262            std::cerr << "Error closing " << filename
1263                      << ", error = " << out->geterror() << "\n";
1264            return;
1265        }
1266\end{code}
1267
1268
1269
1270\section{\ImageOutput Class Reference}
1271\label{sec:imageoutput:reference}
1272
1273\apiitem{static std::unique_ptr<ImageOutput> {\ce create} (const std::string \&filename, \\
1274\bigspc\bigspc\spc const std::string \&plugin_searchpath="")}
1275
1276Create an \ImageOutput that can be used to write an image file.  The
1277type of image file (and hence, the particular subclass of \ImageOutput
1278returned, and the plugin that contains its methods) is inferred from the
1279extension of the file name.  The {\kw plugin_searchpath} parameter is a
1280colon-separated list of directories to search for \product plugin
1281DSO/DLL's.
1282\apiend
1283
1284\apiitem{const char * {\ce format_name} ()}
1285Returns the canonical name of the format that this \ImageOutput
1286instance is capable of writing.
1287\apiend
1288
1289\apiitem{int {\ce supports} (string_view feature) const}
1290\label{sec:supportsfeaturelist}
1291Given the name of a \emph{feature}, tells if this \ImageOutput  instance
1292supports that feature.  Most queries will simply return 0 for ``doesn't
1293support the feature'' and nonzero for ``supports the feature,'' but it is
1294acceptable to have queries return other nonzero integers to indicate varying
1295degrees of support or limits (but those queries should be clearly documented
1296as such). The following features are recognized by this query:
1297\begin{description}
1298\item[\spc] \spc
1299\item[\rm \qkw{tiles}] Is this plugin able to write tiled images?
1300\item[\rm \qkw{rectangles}] Can this plugin accept arbitrary rectangular
1301  pixel regions (via {\kw write_rectangle()})?  False indicates that
1302  pixels must be transmitted via \writescanline (if
1303  scanline-oriented) or \writetile (if tile-oriented, and only if
1304  {\kw supports("tiles")} returns true).
1305\item[\rm \qkw{random_access}] May tiles or scanlines be written in any
1306  order?  False indicates that they must be in successive order.
1307\item[\rm \qkw{multiimage}] Does this format support multiple subimages
1308  within a single file?
1309\item[\rm \qkw{appendsubimage}] Does this format support multiple
1310  subimages that can be successively appended at will, without needing
1311  to pre-declare the number and specifications the subimages when the
1312  file is first opened?
1313\item[\rm \qkw{mipmap}] Does this format support resolutions per
1314  image/subimage (MIP-map levels)?
1315\item[\rm \qkw{volumes}] Does this format support ``3D'' pixel arrays
1316  (a.k.a.\ volume images)?
1317\item[\rm \qkw{alpha}] Does this format support an alpha channel?
1318\item[\rm \qkw{nchannels}] Does this format support an arbitrary number
1319  of channels (beyond RGBA)?
1320\item[\rm \qkw{rewrite}] Does this plugin allow the same scanline or
1321  tile to be sent more than once?  Generally this is true for plugins
1322  that implement some sort of interactive display, rather than a saved
1323  image file.
1324\item[\rm \qkw{empty}] Does this plugin support passing a NULL data
1325  pointer to the various {\kw write} routines to indicate that the
1326  entire data block is composed of pixels with value zero.  Plugins
1327  that support this achieve a speedup when passing blank scanlines or
1328  tiles (since no actual data needs to be transmitted or converted).
1329\item[\rm \qkw{channelformats}] Does this format writer support per-channel
1330  data formats, respecting the \ImageSpec's {\cf channelformats}
1331  field?  (If not, it only accepts a single data format for all
1332  channels and will ignore the {\cf channelformats} field of the spec.)
1333\item[\rm \qkw{displaywindow}] Does the image format support specifying
1334  a display (``full'') window that is distinct from the pixel data
1335  window?
1336\item[\rm \qkw{origin}] Does the image format support specifying
1337  a pixel window origin (i.e., nonzero \ImageSpec {\cf x}, {\cf y},
1338  {\cf z})?
1339\item[\rm \qkw{negativeorigin}] Does the image format allow pixel
1340  and data window origins (i.e., nonzero \ImageSpec {\cf x}, {\cf y},
1341  {\cf z}, {\cf full_x}, {\cf full_y}, {\cf full_z}) to have
1342  negative values?
1343\item[\rm \qkw{deepdata}] Does the image format allow ``deep'' data
1344  consisting of multiple values per pixel (and potentially a differing
1345  number of values from pixel to pixel)?
1346\item[\rm \qkw{arbitrary_metadata}] Does the image file format allow
1347  metadata with arbitrary names (and either arbitrary, or a reasonable set
1348  of, data types)? (Versus the file format supporting only a fixed list of
1349  specific metadata names/values?
1350\item[\rm \qkw{exif}] Does the image file format support Exif camera data
1351  (either specifically, or via arbitrary named metadata)?
1352\item[\rm \qkw{iptc}] Does the image file format support IPTC data
1353  (either specifically, or via arbitrary named metadata)?
1354\item[\rm \qkw{ioproxy}] Does the image file format support writing
1355  to an {\cf IOProxy}?
1356\end{description}
1357
1358\noindent This list of queries may be extended in future releases.
1359Since this can be done simply by recognizing new query strings, and does
1360not require any new API entry points, addition of support for new
1361queries does not break ``link compatibility'' with previously-compiled
1362plugins.
1363\apiend
1364
1365\apiitem{bool {\ce open} (const std::string \&name, const ImageSpec \&newspec,\\
1366\bigspc  OpenMode mode=Create)}
1367\label{sec:imageoutputopen}
1368
1369Open the file with given {\kw name}, with resolution and other format
1370data as given in {\kw newspec}.  This function returns {\kw true} for
1371success, {\kw false} for failure.  Note that it is legal to call
1372{\kw open()} multiple times on the same file without a call to
1373{\kw close()}, if it supports multiimage and {\kw mode} is
1374{\kw AppendSubimage}, or if it supports MIP-maps and {\kw mode} is
1375{\kw AppendMIPLevel} -- this is interpreted as appending a subimage, or
1376a MIP level to the current subimage, respectively.
1377\apiend
1378
1379\apiitem{bool {\ce open} (const std::string \&name, int subimages,
1380 const ImageSpec *specs)}
1381Open the file with given {\cf name}, expecting to have a given total
1382number of subimages, described by {\cf specs[0..subimages-1]}.  Return
1383{\cf true} for success, {\cf false} for failure.  Upon success, the
1384first subimage will be open and ready for transmission of
1385pixels.  Subsequent subimages will be denoted with the usual
1386call of {\cf open(name,spec,AppendSubimage)} (and MIP levels by
1387{\cf open(name,spec,AppendMIPLevel)}).
1388
1389The purpose of this call is to accommodate format-writing libraries that
1390must know the number and specifications of the subimages upon first
1391opening the file; such formats can be detected by
1392\begin{code}
1393    supports("multiimage") && ! supports("appendsubimage")
1394\end{code}
1395The individual specs passed to the appending {\cf open()} calls for
1396subsequent subimages must match the ones originally passed.
1397\apiend
1398
1399
1400\apiitem{const ImageSpec \& {\ce spec} ()}
1401Returns the spec internally associated with this currently open
1402\ImageOutput.
1403\apiend
1404
1405\apiitem{bool {\ce close} ()}
1406Closes the currently open file associated with this \ImageOutput
1407and frees any memory or resources associated with it.
1408\apiend
1409
1410\apiitem{bool {\ce write_scanline} (int y, int z, TypeDesc format,
1411     const void *data, \\
1412\bigspc stride_t xstride=AutoStride)}
1413
1414Write the scanline that includes pixels $(*,y,z)$ from {\cf data}.  For
14152D non-volume images, $z$ is ignored.
1416The {\cf xstride} value gives the data spacing of adjacent pixels (in
1417bytes).  Strides set to the special value {\kw AutoStride} imply
1418contiguous data, i.e., \\
1419\spc {\kw xstride} $=$ {\kw spec.nchannels * format.size()} \\
1420
1421This method automatically converts the data from the specified {\kw format}
1422to the actual output format of the file.
1423If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data is assumed to
1424already be in the file's native format (including per-channel formats,
1425as specified in the \ImageSpec's {\cf channelformats} field, if applicable).
1426Return {\kw true} for success, {\kw false} for failure.
1427It is a failure to call \writescanline with an
1428out-of-order scanline if this format driver does not support random
1429access.
1430\apiend
1431
1432\apiitem{bool {\ce write_scanlines} (int ybegin, int yend, int z, \\
1433\bigspc TypeDesc format,
1434     const void *data, \\
1435\bigspc stride_t xstride=AutoStride, stride_t ystride=AutoStride)}
1436
1437Write a block of scanlines that include pixels $(*,y,z)$,
1438where ${\mathit ybegin} \le y < {\mathit yend}$.  This is essentially
1439identical to {\cf write_scanline()}, except that it can write more than
1440one scanline at a time, which may be more efficient for certain
1441image format writers.
1442
1443For 2D non-volume images, $z$ is ignored.  The {\kw xstride} value gives
1444the distance between successive pixels (in bytes), and {\kw ystride}
1445gives the distance between successive scanlines.  Strides set to the
1446special value {\kw AutoStride} imply contiguous data, i.e., \\
1447 \spc {\kw xstride} $=$ {\kw spec.nchannels*format.size()} \\ \spc {\kw ystride} $=$ {\kw spec.width*xstride}
1448
1449This method automatically converts the data from the specified {\kw format}
1450to the actual output format of the file.
1451If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data is assumed to
1452already be in the file's native format (including per-channel formats,
1453as specified in the \ImageSpec's {\cf channelformats} field, if applicable).
1454Return {\kw true} for success, {\kw false} for failure.
1455It is a failure to call \writescanline with an
1456out-of-order scanline if this format driver does not support random
1457access.
1458\apiend
1459
1460\apiitem{bool {\ce write_tile} (int x, int y, int z, TypeDesc format,
1461                             const void *data, \\ \bigspc stride_t xstride=AutoStride,
1462                             stride_t ystride=AutoStride, \\ \bigspc stride_t zstride=AutoStride)}
1463
1464Write the tile with $(x,y,z)$ as the upper left corner.  For 2D
1465non-volume images, $z$ is ignored.  The three stride values give the
1466distance (in bytes) between successive pixels, scanlines, and volumetric
1467slices, respectively.  Strides set to the special value {\kw AutoStride}
1468imply contiguous data in the shape of a full tile, i.e., \\
1469\spc {\kw xstride} $=$ {\kw spec.nchannels * format.size()} \\
1470\spc {\kw ystride} $=$ {\kw xstride * spec.tile_width} \\
1471\spc {\kw zstride} $=$ {\kw ystride * spec.tile_height} \\
1472This method automatically converts the
1473data from the specified {\kw format} to the actual output format of the
1474file.
1475If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data is assumed to
1476already be in the file's native format (including per-channel formats,
1477as specified in the \ImageSpec's {\cf channelformats} field, if applicable).
1478Return {\kw true} for success, {\kw false} for failure.  It is a
1479failure to call \writetile with an out-of-order tile if this
1480format driver does not support random access.
1481
1482This function returns {\cf true} if it successfully writes the tile,
1483otherwise {\cf false} for a failure.
1484The call will fail if the image is not tiled, or if $(x,y,z)$ is not
1485actually a tile boundary.
1486\apiend
1487
1488\apiitem{bool {\ce write_tiles} (int xbegin, int xend, int ybegin, int yend,\\
1489\bigspc int zbegin, int zend, TypeDesc format, const void *data, \\
1490\bigspc stride_t xstride=AutoStride, stride_t ystride=AutoStride, \\
1491\bigspc stride_t zstride=AutoStride)}
1492
1493Write the tiles that include pixels {\kw xbegin} $\le x <$ {\kw xend},
1494{\kw ybegin} $\le y <$ {\kw yend}, {\kw zbegin} $\le z <$ {\kw zend}
1495from {\kw data},
1496converting if necessary from {\kw format} specified into the file's
1497native data format.
1498If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data will be assumed
1499to already be in the native format (including per-channel formats, if applicable).
1500The stride values
1501give the data spacing of adjacent pixels, scanlines, and volumetric
1502slices, respectively (measured in bytes).  Strides set to the special
1503value of {\kw AutoStride} imply contiguous data in the shape of the
1504region specified, i.e., \\
1505\spc {\kw xstride} $=$ {\kw spec.nchannels * spec.pixel_size()} \\
1506\spc {\kw ystride} $=$ {\kw xstride * (xend - xbegin)} \\
1507\spc {\kw zstride} $=$ {\kw ystride * (yend - ybegin)} \\
1508The data for those tiles is assumed to be in the usual image order, as if
1509it were just one big tile, and not ``paded'' to a whole multiple of the tile size.
1510
1511This function returns {\cf true} if it successfully writes the tiles,
1512otherwise {\cf false} for a failure.
1513The call will fail if the image is not tiled, or if the pixel ranges
1514do not fall along tile (or image) boundaries, or if it is not a valid
1515tile range.
1516\apiend
1517
1518\apiitem{bool {\ce write_rectangle} ({\small int xbegin, int xend, int ybegin, int yend, \\ \bigspc
1519                                  int zbegin, int zend,} TypeDesc format,
1520                                  const void *data, \\ \bigspc stride_t xstride=AutoStride,
1521                                  stride_t ystride=AutoStride, \\
1522                                  \bigspc stride_t zstride=AutoStride)}
1523
1524Write pixels covering the range that includes pixels {\kw xbegin} $\le x <$ {\kw xend},
1525{\kw ybegin} $\le y <$ {\kw yend}, {\kw zbegin} $\le z <$ {\kw zend}.
1526The three stride values give the distance
1527(in bytes) between successive pixels, scanlines, and volumetric slices,
1528respectively.  Strides set to the special value {\kw AutoStride} imply
1529contiguous data, i.e.,\\
1530\spc {\kw xstride} $=$ {\kw spec.nchannels*format.size()} \\
1531\spc {\kw ystride} $=$ {\kw xstride*(xend-xbegin)} \\
1532\spc {\kw zstride} $=$ {\kw ystride*(yend-ybegin)}\\
1533This method automatically converts the data from the specified
1534{\kw format} to the actual output format of the file.
1535If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data is assumed to
1536already be in the file's native format (including per-channel formats,
1537as specified in the \ImageSpec's {\cf channelformats} field, if applicable).
1538Return {\kw true}
1539for success, {\kw false} for failure.  It is a failure to call
1540{\kw write_rectangle} for a format plugin that does not return true for
1541{\kw supports("rectangles")}.
1542
1543\apiend
1544
1545\apiitem{bool {\ce write_image} (TypeDesc format, const void *data, \\
1546                              \bigspc stride_t xstride=AutoStride, stride_t ystride=AutoStride,
1547                              \\ \bigspc stride_t zstride=AutoStride, \\
1548                              \bigspc ProgressCallback progress_callback=NULL,\\
1549                              \bigspc void *progress_callback_data=NULL)}
1550
1551Write the entire image of {\kw spec.width} $\times$ {\kw spec.height}
1552$\times$ {\kw spec.depth}
1553pixels, with the given strides and in the desired format.
1554If {\cf format} is {\cf TypeDesc::UNKNOWN}, the data is assumed to
1555already be in the file's native format (including per-channel formats,
1556as specified in the \ImageSpec's {\cf channelformats} field, if applicable).
1557Strides set to the special value {\kw AutoStride} imply contiguous data,
1558i.e., \\
1559\spc {\kw xstride} $=$ {\kw spec.nchannels * format.size()} \\
1560\spc {\kw ystride} $=$ {\kw xstride * spec.width} \\
1561\spc {\kw zstride} $=$ {\kw ystride * spec.height}\\
1562The function will internally either call \writescanline or
1563\writetile, depending on whether the file is scanline- or
1564tile-oriented.
1565
1566Because this may be an expensive operation, a progress callback may be passed.
1567Periodically, it will be called as follows:
1568\begin{code}
1569        progress_callback (progress_callback_data, float done)
1570\end{code}
1571\noindent where \emph{done} gives the portion of the image
1572(between 0.0 and 1.0) that has been written thus far.
1573
1574\apiend
1575
1576
1577\apiitem{bool {\ce write_deep_scanlines} (int ybegin, int yend, int z, \\
1578\bigspc const DeepData \&deepdata) \\
1579bool {\ce write_deep_tiles} (int xbegin, int xend, int ybegin, int yend,\\
1580\bigspc int zbegin, int zend, const DeepData \&deepdata) \\
1581bool {\ce write_deep_image} (const DeepData \&deepdata)}
1582Write deep data for a block of scanlines, a block of tiles, or an entire
1583image (analogously to the usual {\cf write_scanlines}, {\cf write_tiles},
1584and {\cf write_image}, but with deep data).
1585Return {\kw true} for success, {\kw false} for failure.
1586\apiend
1587
1588
1589\apiitem{bool {\ce copy_image} (ImageInput *in)}
1590
1591Read the current subimage of {\cf in}, and write it as the next subimage
1592of {\cf *this}, in a way that is efficient and does not alter pixel
1593values, if at all possible.  Both {\cf in} and {\cf this} must be a
1594properly-opened \ImageInput and \ImageOutput, respectively, and their
1595current images must match in size and number of channels.  Return {\cf true}
1596if it works ok, {\cf false} if for some reason the operation wasn't possible.
1597
1598If a particular \ImageOutput implementation does not supply a
1599{\cf copy_image} method, it will inherit the default implementation,
1600which is to simply read scanlines or tiles from {\cf in} and write
1601them to {\cf *this}.  However, some file format implementations may have a
1602special technique for directly copying raw pixel data from the
1603input to the output, when both input and output are the same
1604file type and the same data format.  This can be more efficient
1605than {\cf in->read_image} followed by {\cf out->write_image}, and avoids any
1606unintended pixel alterations, especially for formats that use
1607lossy compression.
1608\apiend
1609
1610\apiitem{int {\ce send_to_output} (const char *format, ...)}
1611General message passing between client and image output server.
1612This is currently undefined and is reserved for future use.
1613\apiend
1614
1615\apiitem{int {\ce send_to_client} (const char *format, ...)}
1616General message passing between client and image output server.
1617This is currently undefined and is reserved for future use.
1618\apiend
1619
1620\apiitem{void {\ce threads} (int n) \\
1621int {\ce threads} () const}
1622\index{threads}
1623Get or set the threading policy for this \ImageOutput, controlling the
1624maximum amount of parallelizing thread ``fan-out'' that might occur during
1625large write operations. The default of 0 means that the global
1626{\cf attribute("threads")} value should be used (which itself defaults to
1627using as many threads as cores; see Section~\ref{sec:attribute:threads}).
1628
1629The main reason to change this value is to set it to 1 to indicate that the
1630calling thread should do all the work rather than spawning new threads. That
1631is probably the desired behavior in situations where the calling application
1632has already spawned multiple worker threads.
1633\apiend
1634
1635\apiitem{std::string {\ce geterror} ()}
1636\index{error checking}
1637Returns the current error string describing what went wrong if
1638any of the public methods returned {\kw false} indicating an error.
1639(Hopefully the implementation plugin called {\kw error()} with a
1640helpful error message.)
1641\apiend
1642
1643
1644
1645\index{Image I/O API|)}
1646
1647\chapwidthend
1648