PNG-Writing Demo Program
The demo program I present here is intentionally more limited than it
should be if it were a ``real'' program, in order that the basic concepts
of writing PNG images with libpng not be lost in the details. For simplicity's
sake, I chose to write a basic command-line image-conversion program in ANSI C,
with the PNG-specific ``back end'' code in one file (writepng.c) and
the single, cross-platform ``front end'' in another file (wpng.c).
As with the PNG-reading demo programs, this uses libpng, which is very
complete, well-tested, and by far the most commonly used PNG library.
This program also keeps all image-related variables in a single struct;
as with the one described in Chapter 14, "Reading PNG Images Progressively", this approach would enable a
multithreaded program to handle several images at the same time. Finally,
wpng uses NetPBM (or PBMplus) binary files for input, since there
are few image formats that are simpler to read (or write, for that matter).
But recall from Chapter 5, "Applications: Image Converters", that
there is already an extremely capable NetPBM conversion program called
pnmtopng, by Alexander Lehmann and Willem van Schaik. It
supports practically all PNG chunks and all possible variants of image
data, and its source code is freely available and reusable, subject to
minimal restrictions. Rather than duplicate many of its functions, we
chose to stick to a minimal subset and instead concentrate on a few
features not currently supported[103]
by the larger program: incremental (or progressive) conversion, automatic
timestamping, interactive input of text fields, and support for a very
unofficial NetPBM extension format: type P8 files, containing 32-bit
RGBA data. Supported PNG output types include basic 8-bit-per-sample
grayscale, RGB and RGBA images, either interlaced or not. The program
will write a gamma chunk if the user supplies an explicit value, but not
otherwise; it cannot know a priori in what color space the original
NetPBM image was created. The background chunk is also supported if the
user supplies a background color, but it is ignored if the input image has
no alpha channel.
Readers with more advanced needs should study pnmtopng, which can
be found on the PNG home site:
http://www.libpng.org/pub/png/apps/pnmtopng.html.
It includes such
features as rescaling low-bit-depth samples, reordering the palette so that
opaque entries of the tRNS chunk may be omitted, and support for explicitly
specifying a separate PGM file as the alpha channel. libpng and zlib can
both be found in the same location.
|