Alien-FreeImage

 view release on metacpan or  search on metacpan

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN

The data format returned by the decompressor is the same in all details,
except that colormapped output is supported.  (Again, a JPEG file is never
colormapped.  But you can ask the decompressor to perform on-the-fly color
quantization to deliver colormapped output.)  If you request colormapped
output then the returned data array contains a single JSAMPLE per pixel;
its value is an index into a color map.  The color map is represented as
a 2-D JSAMPARRAY in which each row holds the values of one color component,
that is, colormap[i][j] is the value of the i'th color component for pixel
value (map index) j.  Note that since the colormap indexes are stored in
JSAMPLEs, the maximum number of colors is limited by the size of JSAMPLE
(ie, at most 256 colors for an 8-bit JPEG library).


Compression details
-------------------

Here we revisit the JPEG compression outline given in the overview.

1. Allocate and initialize a JPEG compression object.

A JPEG compression object is a "struct jpeg_compress_struct".  (It also has
a bunch of subsidiary structures which are allocated via malloc(), but the
application doesn't control those directly.)  This struct can be just a local
variable in the calling routine, if a single routine is going to execute the
whole JPEG compression sequence.  Otherwise it can be static or allocated
from malloc().

You will also need a structure representing a JPEG error handler.  The part
of this that the library cares about is a "struct jpeg_error_mgr".  If you
are providing your own error handler, you'll typically want to embed the
jpeg_error_mgr struct in a larger structure; this is discussed later under
"Error handling".  For now we'll assume you are just using the default error
handler.  The default error handler will print JPEG error/warning messages
on stderr, and it will call exit() if a fatal error occurs.

You must initialize the error handler structure, store a pointer to it into
the JPEG object's "err" field, and then call jpeg_create_compress() to
initialize the rest of the JPEG object.

Typical code for this step, if you are using the default error handler, is

	struct jpeg_compress_struct cinfo;
	struct jpeg_error_mgr jerr;
	...
	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_compress(&cinfo);

jpeg_create_compress allocates a small amount of memory, so it could fail
if you are out of memory.  In that case it will exit via the error handler;
that's why the error handler must be initialized first.


2. Specify the destination for the compressed data (eg, a file).

As previously mentioned, the JPEG library delivers compressed data to a
"data destination" module.  The library includes one data destination
module which knows how to write to a stdio stream.  You can use your own
destination module if you want to do something else, as discussed later.

If you use the standard destination module, you must open the target stdio
stream beforehand.  Typical code for this step looks like:

	FILE * outfile;
	...
	if ((outfile = fopen(filename, "wb")) == NULL) {
	    fprintf(stderr, "can't open %s\n", filename);
	    exit(1);
	}
	jpeg_stdio_dest(&cinfo, outfile);

where the last line invokes the standard destination module.

WARNING: it is critical that the binary compressed data be delivered to the
output file unchanged.  On non-Unix systems the stdio library may perform
newline translation or otherwise corrupt binary data.  To suppress this
behavior, you may need to use a "b" option to fopen (as shown above), or use
setmode() or another routine to put the stdio stream in binary mode.  See
cjpeg.c and djpeg.c for code that has been found to work on many systems.

You can select the data destination after setting other parameters (step 3),
if that's more convenient.  You may not change the destination between
calling jpeg_start_compress() and jpeg_finish_compress().


3. Set parameters for compression, including image size & colorspace.

You must supply information about the source image by setting the following
fields in the JPEG object (cinfo structure):

	image_width		Width of image, in pixels
	image_height		Height of image, in pixels
	input_components	Number of color channels (samples per pixel)
	in_color_space		Color space of source image

The image dimensions are, hopefully, obvious.  JPEG supports image dimensions
of 1 to 64K pixels in either direction.  The input color space is typically
RGB or grayscale, and input_components is 3 or 1 accordingly.  (See "Special
color spaces", later, for more info.)  The in_color_space field must be
assigned one of the J_COLOR_SPACE enum constants, typically JCS_RGB or
JCS_GRAYSCALE.

JPEG has a large number of compression parameters that determine how the
image is encoded.  Most applications don't need or want to know about all
these parameters.  You can set all the parameters to reasonable defaults by
calling jpeg_set_defaults(); then, if there are particular values you want
to change, you can do so after that.  The "Compression parameter selection"
section tells about all the parameters.

You must set in_color_space correctly before calling jpeg_set_defaults(),
because the defaults depend on the source image colorspace.  However the
other three source image parameters need not be valid until you call
jpeg_start_compress().  There's no harm in calling jpeg_set_defaults() more
than once, if that happens to be convenient.

Typical code for a 24-bit RGB source image is

	cinfo.image_width = Width; 	/* image width and height, in pixels */
	cinfo.image_height = Height;
	cinfo.input_components = 3;	/* # of color components per pixel */
	cinfo.in_color_space = JCS_RGB; /* colorspace of input image */

	jpeg_set_defaults(&cinfo);
	/* Make optional parameter settings here */


4. jpeg_start_compress(...);

After you have established the data destination and set all the necessary
source image info and other parameters, call jpeg_start_compress() to begin
a compression cycle.  This will initialize internal state, allocate working
storage, and emit the first few bytes of the JPEG datastream header.

Typical code:

	jpeg_start_compress(&cinfo, TRUE);

The "TRUE" parameter ensures that a complete JPEG interchange datastream
will be written.  This is appropriate in most cases.  If you think you might
want to use an abbreviated datastream, read the section on abbreviated
datastreams, below.

Once you have called jpeg_start_compress(), you may not alter any JPEG
parameters or other fields of the JPEG object until you have completed
the compression cycle.


5. while (scan lines remain to be written)
	jpeg_write_scanlines(...);

Now write all the required image data by calling jpeg_write_scanlines()
one or more times.  You can pass one or more scanlines in each call, up
to the total image height.  In most applications it is convenient to pass
just one or a few scanlines at a time.  The expected format for the passed
data is discussed under "Data formats", above.

Image data should be written in top-to-bottom scanline order.  The JPEG spec
contains some weasel wording about how top and bottom are application-defined
terms (a curious interpretation of the English language...) but if you want
your files to be compatible with everyone else's, you WILL use top-to-bottom
order.  If the source data must be read in bottom-to-top order, you can use
the JPEG library's virtual array mechanism to invert the data efficiently.
Examples of this can be found in the sample application cjpeg.

The library maintains a count of the number of scanlines written so far
in the next_scanline field of the JPEG object.  Usually you can just use
this variable as the loop counter, so that the loop test looks like
"while (cinfo.next_scanline < cinfo.image_height)".

Code for this step depends heavily on the way that you store the source data.
example.c shows the following code for the case of a full-size 2-D source
array containing 3-byte RGB pixels:

	JSAMPROW row_pointer[1];	/* pointer to a single row */
	int row_stride;			/* physical row width in buffer */

	row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */

	while (cinfo.next_scanline < cinfo.image_height) {
	    row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
	    jpeg_write_scanlines(&cinfo, row_pointer, 1);
	}

jpeg_write_scanlines() returns the number of scanlines actually written.
This will normally be equal to the number passed in, so you can usually
ignore the return value.  It is different in just two cases:
  * If you try to write more scanlines than the declared image height,
    the additional scanlines are ignored.
  * If you use a suspending data destination manager, output buffer overrun
    will cause the compressor to return before accepting all the passed lines.
    This feature is discussed under "I/O suspension", below.  The normal
    stdio destination manager will NOT cause this to happen.
In any case, the return value is the same as the change in the value of
next_scanline.


6. jpeg_finish_compress(...);

After all the image data has been written, call jpeg_finish_compress() to
complete the compression cycle.  This step is ESSENTIAL to ensure that the
last bufferload of data is written to the data destination.
jpeg_finish_compress() also releases working memory associated with the JPEG
object.

Typical code:

	jpeg_finish_compress(&cinfo);

If using the stdio destination manager, don't forget to close the output
stdio stream (if necessary) afterwards.

If you have requested a multi-pass operating mode, such as Huffman code
optimization, jpeg_finish_compress() will perform the additional passes using
data buffered by the first pass.  In this case jpeg_finish_compress() may take
quite a while to complete.  With the default compression parameters, this will
not happen.

It is an error to call jpeg_finish_compress() before writing the necessary
total number of scanlines.  If you wish to abort compression, call
jpeg_abort() as discussed below.

After completing a compression cycle, you may dispose of the JPEG object
as discussed next, or you may use it to compress another image.  In that case
return to step 2, 3, or 4 as appropriate.  If you do not change the
destination manager, the new datastream will be written to the same target.
If you do not change any JPEG parameters, the new datastream will be written
with the same parameters as before.  Note that you can change the input image

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN


	jpeg_destroy_compress(&cinfo);


8. Aborting.

If you decide to abort a compression cycle before finishing, you can clean up
in either of two ways:

* If you don't need the JPEG object any more, just call
  jpeg_destroy_compress() or jpeg_destroy() to release memory.  This is
  legitimate at any point after calling jpeg_create_compress() --- in fact,
  it's safe even if jpeg_create_compress() fails.

* If you want to re-use the JPEG object, call jpeg_abort_compress(), or call
  jpeg_abort() which works on both compression and decompression objects.
  This will return the object to an idle state, releasing any working memory.
  jpeg_abort() is allowed at any time after successful object creation.

Note that cleaning up the data destination, if required, is your
responsibility; neither of these routines will call term_destination().
(See "Compressed data handling", below, for more about that.)

jpeg_destroy() and jpeg_abort() are the only safe calls to make on a JPEG
object that has reported an error by calling error_exit (see "Error handling"
for more info).  The internal state of such an object is likely to be out of
whack.  Either of these two routines will return the object to a known state.


Decompression details
---------------------

Here we revisit the JPEG decompression outline given in the overview.

1. Allocate and initialize a JPEG decompression object.

This is just like initialization for compression, as discussed above,
except that the object is a "struct jpeg_decompress_struct" and you
call jpeg_create_decompress().  Error handling is exactly the same.

Typical code:

	struct jpeg_decompress_struct cinfo;
	struct jpeg_error_mgr jerr;
	...
	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_decompress(&cinfo);

(Both here and in the IJG code, we usually use variable name "cinfo" for
both compression and decompression objects.)


2. Specify the source of the compressed data (eg, a file).

As previously mentioned, the JPEG library reads compressed data from a "data
source" module.  The library includes one data source module which knows how
to read from a stdio stream.  You can use your own source module if you want
to do something else, as discussed later.

If you use the standard source module, you must open the source stdio stream
beforehand.  Typical code for this step looks like:

	FILE * infile;
	...
	if ((infile = fopen(filename, "rb")) == NULL) {
	    fprintf(stderr, "can't open %s\n", filename);
	    exit(1);
	}
	jpeg_stdio_src(&cinfo, infile);

where the last line invokes the standard source module.

WARNING: it is critical that the binary compressed data be read unchanged.
On non-Unix systems the stdio library may perform newline translation or
otherwise corrupt binary data.  To suppress this behavior, you may need to use
a "b" option to fopen (as shown above), or use setmode() or another routine to
put the stdio stream in binary mode.  See cjpeg.c and djpeg.c for code that
has been found to work on many systems.

You may not change the data source between calling jpeg_read_header() and
jpeg_finish_decompress().  If you wish to read a series of JPEG images from
a single source file, you should repeat the jpeg_read_header() to
jpeg_finish_decompress() sequence without reinitializing either the JPEG
object or the data source module; this prevents buffered input data from
being discarded.


3. Call jpeg_read_header() to obtain image info.

Typical code for this step is just

	jpeg_read_header(&cinfo, TRUE);

This will read the source datastream header markers, up to the beginning
of the compressed data proper.  On return, the image dimensions and other
info have been stored in the JPEG object.  The application may wish to
consult this information before selecting decompression parameters.

More complex code is necessary if
  * A suspending data source is used --- in that case jpeg_read_header()
    may return before it has read all the header data.  See "I/O suspension",
    below.  The normal stdio source manager will NOT cause this to happen.
  * Abbreviated JPEG files are to be processed --- see the section on
    abbreviated datastreams.  Standard applications that deal only in
    interchange JPEG files need not be concerned with this case either.

It is permissible to stop at this point if you just wanted to find out the
image dimensions and other header info for a JPEG file.  In that case,
call jpeg_destroy() when you are done with the JPEG object, or call
jpeg_abort() to return it to an idle state before selecting a new data
source and reading another header.


4. Set parameters for decompression.

jpeg_read_header() sets appropriate default decompression parameters based on
the properties of the image (in particular, its colorspace).  However, you
may well want to alter these defaults before beginning the decompression.
For example, the default is to produce full color output from a color file.
If you want colormapped output you must ask for it.  Other options allow the
returned image to be scaled and allow various speed/quality tradeoffs to be

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN

Once the parameter values are satisfactory, call jpeg_start_decompress() to
begin decompression.  This will initialize internal state, allocate working
memory, and prepare for returning data.

Typical code is just

	jpeg_start_decompress(&cinfo);

If you have requested a multi-pass operating mode, such as 2-pass color
quantization, jpeg_start_decompress() will do everything needed before data
output can begin.  In this case jpeg_start_decompress() may take quite a while
to complete.  With a single-scan (non progressive) JPEG file and default
decompression parameters, this will not happen; jpeg_start_decompress() will
return quickly.

After this call, the final output image dimensions, including any requested
scaling, are available in the JPEG object; so is the selected colormap, if
colormapped output has been requested.  Useful fields include

	output_width		image width and height, as scaled
	output_height
	out_color_components	# of color components in out_color_space
	output_components	# of color components returned per pixel
	colormap		the selected colormap, if any
	actual_number_of_colors		number of entries in colormap

output_components is 1 (a colormap index) when quantizing colors; otherwise it
equals out_color_components.  It is the number of JSAMPLE values that will be
emitted per pixel in the output arrays.

Typically you will need to allocate data buffers to hold the incoming image.
You will need output_width * output_components JSAMPLEs per scanline in your
output buffer, and a total of output_height scanlines will be returned.

Note: if you are using the JPEG library's internal memory manager to allocate
data buffers (as djpeg does), then the manager's protocol requires that you
request large buffers *before* calling jpeg_start_decompress().  This is a
little tricky since the output_XXX fields are not normally valid then.  You
can make them valid by calling jpeg_calc_output_dimensions() after setting the
relevant parameters (scaling, output color space, and quantization flag).


6. while (scan lines remain to be read)
	jpeg_read_scanlines(...);

Now you can read the decompressed image data by calling jpeg_read_scanlines()
one or more times.  At each call, you pass in the maximum number of scanlines
to be read (ie, the height of your working buffer); jpeg_read_scanlines()
will return up to that many lines.  The return value is the number of lines
actually read.  The format of the returned data is discussed under "Data
formats", above.  Don't forget that grayscale and color JPEGs will return
different data formats!

Image data is returned in top-to-bottom scanline order.  If you must write
out the image in bottom-to-top order, you can use the JPEG library's virtual
array mechanism to invert the data efficiently.  Examples of this can be
found in the sample application djpeg.

The library maintains a count of the number of scanlines returned so far
in the output_scanline field of the JPEG object.  Usually you can just use
this variable as the loop counter, so that the loop test looks like
"while (cinfo.output_scanline < cinfo.output_height)".  (Note that the test
should NOT be against image_height, unless you never use scaling.  The
image_height field is the height of the original unscaled image.)
The return value always equals the change in the value of output_scanline.

If you don't use a suspending data source, it is safe to assume that
jpeg_read_scanlines() reads at least one scanline per call, until the
bottom of the image has been reached.

If you use a buffer larger than one scanline, it is NOT safe to assume that
jpeg_read_scanlines() fills it.  (The current implementation returns only a
few scanlines per call, no matter how large a buffer you pass.)  So you must
always provide a loop that calls jpeg_read_scanlines() repeatedly until the
whole image has been read.


7. jpeg_finish_decompress(...);

After all the image data has been read, call jpeg_finish_decompress() to
complete the decompression cycle.  This causes working memory associated
with the JPEG object to be released.

Typical code:

	jpeg_finish_decompress(&cinfo);

If using the stdio source manager, don't forget to close the source stdio
stream if necessary.

It is an error to call jpeg_finish_decompress() before reading the correct
total number of scanlines.  If you wish to abort decompression, call
jpeg_abort() as discussed below.

After completing a decompression cycle, you may dispose of the JPEG object as
discussed next, or you may use it to decompress another image.  In that case
return to step 2 or 3 as appropriate.  If you do not change the source
manager, the next image will be read from the same source.


8. Release the JPEG decompression object.

When you are done with a JPEG decompression object, destroy it by calling
jpeg_destroy_decompress() or jpeg_destroy().  The previous discussion of
destroying compression objects applies here too.

Typical code:

	jpeg_destroy_decompress(&cinfo);


9. Aborting.

You can abort a decompression cycle by calling jpeg_destroy_decompress() or
jpeg_destroy() if you don't need the JPEG object any more, or
jpeg_abort_decompress() or jpeg_abort() if you want to reuse the object.
The previous discussion of aborting compression cycles applies here too.


Mechanics of usage: include files, linking, etc
-----------------------------------------------

src/Source/LibJPEG/libjpeg.txt  view on Meta::CPAN

JDIMENSION image_width			Width and height of image
JDIMENSION image_height
int num_components			Number of color components
J_COLOR_SPACE jpeg_color_space		Colorspace of image
boolean saw_JFIF_marker			TRUE if a JFIF APP0 marker was seen
  UINT8 JFIF_major_version		Version information from JFIF marker
  UINT8 JFIF_minor_version
  UINT8 density_unit			Resolution data from JFIF marker
  UINT16 X_density
  UINT16 Y_density
boolean saw_Adobe_marker		TRUE if an Adobe APP14 marker was seen
  UINT8 Adobe_transform			Color transform code from Adobe marker

The JPEG color space, unfortunately, is something of a guess since the JPEG
standard proper does not provide a way to record it.  In practice most files
adhere to the JFIF or Adobe conventions, and the decoder will recognize these
correctly.  See "Special color spaces", below, for more info.


The decompression parameters that determine the basic properties of the
returned image are:

J_COLOR_SPACE out_color_space
	Output color space.  jpeg_read_header() sets an appropriate default
	based on jpeg_color_space; typically it will be RGB or grayscale.
	The application can change this field to request output in a different
	colorspace.  For example, set it to JCS_GRAYSCALE to get grayscale
	output from a color file.  (This is useful for previewing: grayscale
	output is faster than full color since the color components need not
	be processed.)  Note that not all possible color space transforms are
	currently implemented; you may need to extend jdcolor.c if you want an
	unusual conversion.

unsigned int scale_num, scale_denom
	Scale the image by the fraction scale_num/scale_denom.  Currently,
	the supported scaling ratios are M/N with all M from 1 to 16, where
	N is the source DCT size, which is 8 for baseline JPEG.  (The library
	design allows for arbitrary scaling ratios but this is not likely
	to be implemented any time soon.)  The values are initialized by
	jpeg_read_header() with the source DCT size.  For baseline JPEG
	this is 8/8.  If you change only the scale_num value while leaving
	the other unchanged, then this specifies the DCT scaled size to be
	applied on the given input.  For baseline JPEG this is equivalent
	to M/8 scaling, since the source DCT size for baseline JPEG is 8.
	Smaller scaling ratios permit significantly faster decoding since
	fewer pixels need be processed and a simpler IDCT method can be used.

boolean quantize_colors
	If set TRUE, colormapped output will be delivered.  Default is FALSE,
	meaning that full-color output will be delivered.

The next three parameters are relevant only if quantize_colors is TRUE.

int desired_number_of_colors
	Maximum number of colors to use in generating a library-supplied color
	map (the actual number of colors is returned in a different field).
	Default 256.  Ignored when the application supplies its own color map.

boolean two_pass_quantize
	If TRUE, an extra pass over the image is made to select a custom color
	map for the image.  This usually looks a lot better than the one-size-
	fits-all colormap that is used otherwise.  Default is TRUE.  Ignored
	when the application supplies its own color map.

J_DITHER_MODE dither_mode
	Selects color dithering method.  Supported values are:
		JDITHER_NONE	no dithering: fast, very low quality
		JDITHER_ORDERED	ordered dither: moderate speed and quality
		JDITHER_FS	Floyd-Steinberg dither: slow, high quality
	Default is JDITHER_FS.  (At present, ordered dither is implemented
	only in the single-pass, standard-colormap case.  If you ask for
	ordered dither when two_pass_quantize is TRUE or when you supply
	an external color map, you'll get F-S dithering.)

When quantize_colors is TRUE, the target color map is described by the next
two fields.  colormap is set to NULL by jpeg_read_header().  The application
can supply a color map by setting colormap non-NULL and setting
actual_number_of_colors to the map size.  Otherwise, jpeg_start_decompress()
selects a suitable color map and sets these two fields itself.
[Implementation restriction: at present, an externally supplied colormap is
only accepted for 3-component output color spaces.]

JSAMPARRAY colormap
	The color map, represented as a 2-D pixel array of out_color_components
	rows and actual_number_of_colors columns.  Ignored if not quantizing.
	CAUTION: if the JPEG library creates its own colormap, the storage
	pointed to by this field is released by jpeg_finish_decompress().
	Copy the colormap somewhere else first, if you want to save it.

int actual_number_of_colors
	The number of colors in the color map.

Additional decompression parameters that the application may set include:

J_DCT_METHOD dct_method
	Selects the algorithm used for the DCT step.  Choices are the same
	as described above for compression.

boolean do_fancy_upsampling
	If TRUE, use direct DCT scaling with DCT size > 8 for upsampling
	of chroma components.
	If FALSE, use only DCT size <= 8 and simple separate upsampling.
	Default is TRUE.
	For better image stability in multiple generation compression cycles
	it is preferable that this value matches the corresponding
	do_fancy_downsampling value in compression.

boolean do_block_smoothing
	If TRUE, interblock smoothing is applied in early stages of decoding
	progressive JPEG files; if FALSE, not.  Default is TRUE.  Early
	progression stages look "fuzzy" with smoothing, "blocky" without.
	In any case, block smoothing ceases to be applied after the first few
	AC coefficients are known to full accuracy, so it is relevant only
	when using buffered-image mode for progressive images.

boolean enable_1pass_quant
boolean enable_external_quant
boolean enable_2pass_quant
	These are significant only in buffered-image mode, which is
	described in its own section below.



( run in 0.703 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )