4 * This file illustrates how to use the IJG code as a subroutine library
5 * to read or write JPEG image files. You should look at this code in
6 * conjunction with the documentation file libjpeg.txt.
8 * This code will not do anything useful as-is, but it may be helpful as a
9 * skeleton for constructing routines that call the JPEG library.
11 * We present these routines in the same coding style used in the JPEG code
12 * (ANSI function definitions, etc); but you are of course free to code your
13 * routines in a different style if you prefer.
16 /* This example was part of the original libjpeg documentation and has been
17 * unchanged since 1994. It is, as described in libjpeg.txt, "heavily
18 * commented skeleton code for calling the JPEG library." It is not meant to
19 * be compiled as a standalone program, since it has no main() function and
20 * does not compress from/decompress to a real image buffer (corollary:
21 * put_scanline_someplace() is not a real function.) First-time users of
22 * libjpeg-turbo would be better served by looking at tjexample.c, which uses
23 * the more straightforward TurboJPEG API, or at cjpeg.c and djpeg.c, which are
24 * examples of libjpeg API usage that can be (and are) compiled into standalone
25 * programs. Note that this example, as well as the examples in cjpeg.c and
26 * djpeg.c, interleave disk I/O with JPEG compression/decompression, so none of
27 * these examples is suitable for benchmarking purposes.
33 * Include file for users of JPEG library.
34 * You will need to have included system headers that define at least
35 * the typedefs FILE and size_t before you can include jpeglib.h.
36 * (stdio.h is sufficient on ANSI-conforming systems.)
37 * You may also wish to include "jerror.h".
43 * <setjmp.h> is used for the optional error recovery mechanism shown in
44 * the second part of the example.
51 /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
53 /* This half of the example shows how to feed data into the JPEG compressor.
54 * We present a minimal version that does not worry about refinements such
55 * as error recovery (the JPEG code will just exit() if it gets an error).
62 * The standard input image format is a rectangular array of pixels, with
63 * each pixel having the same number of "component" values (color channels).
64 * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
65 * If you are working with color data, then the color values for each pixel
66 * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
69 * For this example, we'll assume that this data structure matches the way
70 * our application has stored the image in memory, so we can just pass a
71 * pointer to our image buffer. In particular, let's say that the image is
72 * RGB color and is described by:
75 extern JSAMPLE *image_buffer; /* Points to large array of R,G,B-order data */
76 extern int image_height; /* Number of rows in image */
77 extern int image_width; /* Number of columns in image */
81 * Sample routine for JPEG compression. We assume that the target file name
82 * and a compression quality factor are passed in.
86 write_JPEG_file(char *filename, int quality)
88 /* This struct contains the JPEG compression parameters and pointers to
89 * working space (which is allocated as needed by the JPEG library).
90 * It is possible to have several such structures, representing multiple
91 * compression/decompression processes, in existence at once. We refer
92 * to any one struct (and its associated working data) as a "JPEG object".
94 struct jpeg_compress_struct cinfo;
95 /* This struct represents a JPEG error handler. It is declared separately
96 * because applications often want to supply a specialized error handler
97 * (see the second half of this file for an example). But here we just
98 * take the easy way out and use the standard error handler, which will
99 * print a message on stderr and call exit() if compression fails.
100 * Note that this struct must live as long as the main JPEG parameter
101 * struct, to avoid dangling-pointer problems.
103 struct jpeg_error_mgr jerr;
105 FILE *outfile; /* target file */
106 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
107 int row_stride; /* physical row width in image buffer */
109 /* Step 1: allocate and initialize JPEG compression object */
111 /* We have to set up the error handler first, in case the initialization
112 * step fails. (Unlikely, but it could happen if you are out of memory.)
113 * This routine fills in the contents of struct jerr, and returns jerr's
114 * address which we place into the link field in cinfo.
116 cinfo.err = jpeg_std_error(&jerr);
117 /* Now we can initialize the JPEG compression object. */
118 jpeg_create_compress(&cinfo);
120 /* Step 2: specify data destination (eg, a file) */
121 /* Note: steps 2 and 3 can be done in either order. */
123 /* Here we use the library-supplied code to send compressed data to a
124 * stdio stream. You can also write your own code to do something else.
125 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
126 * requires it in order to write binary files.
128 if ((outfile = fopen(filename, "wb")) == NULL) {
129 fprintf(stderr, "can't open %s\n", filename);
132 jpeg_stdio_dest(&cinfo, outfile);
134 /* Step 3: set parameters for compression */
136 /* First we supply a description of the input image.
137 * Four fields of the cinfo struct must be filled in:
139 cinfo.image_width = image_width; /* image width and height, in pixels */
140 cinfo.image_height = image_height;
141 cinfo.input_components = 3; /* # of color components per pixel */
142 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
143 /* Now use the library's routine to set default compression parameters.
144 * (You must set at least cinfo.in_color_space before calling this,
145 * since the defaults depend on the source color space.)
147 jpeg_set_defaults(&cinfo);
148 /* Now you can set any non-default parameters you wish to.
149 * Here we just illustrate the use of quality (quantization table) scaling:
151 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
153 /* Step 4: Start compressor */
155 /* TRUE ensures that we will write a complete interchange-JPEG file.
156 * Pass TRUE unless you are very sure of what you're doing.
158 jpeg_start_compress(&cinfo, TRUE);
160 /* Step 5: while (scan lines remain to be written) */
161 /* jpeg_write_scanlines(...); */
163 /* Here we use the library's state variable cinfo.next_scanline as the
164 * loop counter, so that we don't have to keep track ourselves.
165 * To keep things simple, we pass one scanline per call; you can pass
166 * more if you wish, though.
168 row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */
170 while (cinfo.next_scanline < cinfo.image_height) {
171 /* jpeg_write_scanlines expects an array of pointers to scanlines.
172 * Here the array is only one element long, but you could pass
173 * more than one scanline at a time if that's more convenient.
175 row_pointer[0] = &image_buffer[cinfo.next_scanline * row_stride];
176 (void)jpeg_write_scanlines(&cinfo, row_pointer, 1);
179 /* Step 6: Finish compression */
181 jpeg_finish_compress(&cinfo);
182 /* After finish_compress, we can close the output file. */
185 /* Step 7: release JPEG compression object */
187 /* This is an important step since it will release a good deal of memory. */
188 jpeg_destroy_compress(&cinfo);
190 /* And we're done! */
197 * In the above loop, we ignored the return value of jpeg_write_scanlines,
198 * which is the number of scanlines actually written. We could get away
199 * with this because we were only relying on the value of cinfo.next_scanline,
200 * which will be incremented correctly. If you maintain additional loop
201 * variables then you should be careful to increment them properly.
202 * Actually, for output to a stdio stream you needn't worry, because
203 * then jpeg_write_scanlines will write all the lines passed (or else exit
204 * with a fatal error). Partial writes can only occur if you use a data
205 * destination module that can demand suspension of the compressor.
206 * (If you don't know what that's for, you don't need it.)
208 * If the compressor requires full-image buffers (for entropy-coding
209 * optimization or a multi-scan JPEG file), it will create temporary
210 * files for anything that doesn't fit within the maximum-memory setting.
211 * (Note that temp files are NOT needed if you use the default parameters.)
212 * On some systems you may need to set up a signal handler to ensure that
213 * temporary files are deleted if the program is interrupted. See libjpeg.txt.
215 * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
216 * files to be compatible with everyone else's. If you cannot readily read
217 * your data in that order, you'll need an intermediate array to hold the
218 * image. See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
219 * source data using the JPEG code's internal virtual-array mechanisms.
224 /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
226 /* This half of the example shows how to read data from the JPEG decompressor.
227 * It's a bit more refined than the above, in that we show:
228 * (a) how to modify the JPEG library's standard error-reporting behavior;
229 * (b) how to allocate workspace using the library's memory manager.
231 * Just to make this example a little different from the first one, we'll
232 * assume that we do not intend to put the whole image into an in-memory
233 * buffer, but to send it line-by-line someplace else. We need a one-
234 * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
235 * memory manager allocate it for us. This approach is actually quite useful
236 * because we don't need to remember to deallocate the buffer separately: it
237 * will go away automatically when the JPEG object is cleaned up.
244 * The JPEG library's standard error handler (jerror.c) is divided into
245 * several "methods" which you can override individually. This lets you
246 * adjust the behavior without duplicating a lot of code, which you might
247 * have to update with each future release.
249 * Our example here shows how to override the "error_exit" method so that
250 * control is returned to the library's caller when a fatal error occurs,
251 * rather than calling exit() as the standard error_exit method does.
253 * We use C's setjmp/longjmp facility to return control. This means that the
254 * routine which calls the JPEG library must first execute a setjmp() call to
255 * establish the return point. We want the replacement error_exit to do a
256 * longjmp(). But we need to make the setjmp buffer accessible to the
257 * error_exit routine. To do this, we make a private extension of the
258 * standard JPEG error handler object. (If we were using C++, we'd say we
259 * were making a subclass of the regular error handler.)
261 * Here's the extended error handler struct:
264 struct my_error_mgr {
265 struct jpeg_error_mgr pub; /* "public" fields */
267 jmp_buf setjmp_buffer; /* for return to caller */
270 typedef struct my_error_mgr *my_error_ptr;
273 * Here's the routine that will replace the standard error_exit method:
277 my_error_exit(j_common_ptr cinfo)
279 /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
280 my_error_ptr myerr = (my_error_ptr)cinfo->err;
282 /* Always display the message. */
283 /* We could postpone this until after returning, if we chose. */
284 (*cinfo->err->output_message) (cinfo);
286 /* Return control to the setjmp point */
287 longjmp(myerr->setjmp_buffer, 1);
291 METHODDEF(int) do_read_JPEG_file(struct jpeg_decompress_struct *cinfo,
295 * Sample routine for JPEG decompression. We assume that the source file name
296 * is passed in. We want to return 1 on success, 0 on error.
300 read_JPEG_file(char *filename)
302 /* This struct contains the JPEG decompression parameters and pointers to
303 * working space (which is allocated as needed by the JPEG library).
305 struct jpeg_decompress_struct cinfo;
307 return do_read_JPEG_file(&cinfo, filename);
311 * We call the libjpeg API from within a separate function, because modifying
312 * the local non-volatile jpeg_decompress_struct instance below the setjmp()
313 * return point and then accessing the instance after setjmp() returns would
314 * result in undefined behavior that may potentially overwrite all or part of
319 do_read_JPEG_file(struct jpeg_decompress_struct *cinfo, char *filename)
321 /* We use our private extension JPEG error handler.
322 * Note that this struct must live as long as the main JPEG parameter
323 * struct, to avoid dangling-pointer problems.
325 struct my_error_mgr jerr;
327 FILE *infile; /* source file */
328 JSAMPARRAY buffer; /* Output row buffer */
329 int row_stride; /* physical row width in output buffer */
331 /* In this example we want to open the input file before doing anything else,
332 * so that the setjmp() error recovery below can assume the file is open.
333 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
334 * requires it in order to read binary files.
337 if ((infile = fopen(filename, "rb")) == NULL) {
338 fprintf(stderr, "can't open %s\n", filename);
342 /* Step 1: allocate and initialize JPEG decompression object */
344 /* We set up the normal JPEG error routines, then override error_exit. */
345 cinfo->err = jpeg_std_error(&jerr.pub);
346 jerr.pub.error_exit = my_error_exit;
347 /* Establish the setjmp return context for my_error_exit to use. */
348 if (setjmp(jerr.setjmp_buffer)) {
349 /* If we get here, the JPEG code has signaled an error.
350 * We need to clean up the JPEG object, close the input file, and return.
352 jpeg_destroy_decompress(cinfo);
356 /* Now we can initialize the JPEG decompression object. */
357 jpeg_create_decompress(cinfo);
359 /* Step 2: specify data source (eg, a file) */
361 jpeg_stdio_src(cinfo, infile);
363 /* Step 3: read file parameters with jpeg_read_header() */
365 (void)jpeg_read_header(cinfo, TRUE);
366 /* We can ignore the return value from jpeg_read_header since
367 * (a) suspension is not possible with the stdio data source, and
368 * (b) we passed TRUE to reject a tables-only JPEG file as an error.
369 * See libjpeg.txt for more info.
372 /* Step 4: set parameters for decompression */
374 /* In this example, we don't need to change any of the defaults set by
375 * jpeg_read_header(), so we do nothing here.
378 /* Step 5: Start decompressor */
380 (void)jpeg_start_decompress(cinfo);
381 /* We can ignore the return value since suspension is not possible
382 * with the stdio data source.
385 /* We may need to do some setup of our own at this point before reading
386 * the data. After jpeg_start_decompress() we have the correct scaled
387 * output image dimensions available, as well as the output colormap
388 * if we asked for color quantization.
389 * In this example, we need to make an output work buffer of the right size.
391 /* JSAMPLEs per row in output buffer */
392 row_stride = cinfo->output_width * cinfo->output_components;
393 /* Make a one-row-high sample array that will go away when done with image */
394 buffer = (*cinfo->mem->alloc_sarray)
395 ((j_common_ptr)cinfo, JPOOL_IMAGE, row_stride, 1);
397 /* Step 6: while (scan lines remain to be read) */
398 /* jpeg_read_scanlines(...); */
400 /* Here we use the library's state variable cinfo->output_scanline as the
401 * loop counter, so that we don't have to keep track ourselves.
403 while (cinfo->output_scanline < cinfo->output_height) {
404 /* jpeg_read_scanlines expects an array of pointers to scanlines.
405 * Here the array is only one element long, but you could ask for
406 * more than one scanline at a time if that's more convenient.
408 (void)jpeg_read_scanlines(cinfo, buffer, 1);
409 /* Assume put_scanline_someplace wants a pointer and sample count. */
410 put_scanline_someplace(buffer[0], row_stride);
413 /* Step 7: Finish decompression */
415 (void)jpeg_finish_decompress(cinfo);
416 /* We can ignore the return value since suspension is not possible
417 * with the stdio data source.
420 /* Step 8: Release JPEG decompression object */
422 /* This is an important step since it will release a good deal of memory. */
423 jpeg_destroy_decompress(cinfo);
425 /* After finish_decompress, we can close the input file.
426 * Here we postpone it until after no more JPEG errors are possible,
427 * so as to simplify the setjmp error logic above. (Actually, I don't
428 * think that jpeg_destroy can do an error exit, but why assume anything...)
432 /* At this point you may want to check to see whether any corrupt-data
433 * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
436 /* And we're done! */
444 * In the above code, we ignored the return value of jpeg_read_scanlines,
445 * which is the number of scanlines actually read. We could get away with
446 * this because we asked for only one line at a time and we weren't using
447 * a suspending data source. See libjpeg.txt for more info.
449 * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
450 * we should have done it beforehand to ensure that the space would be
451 * counted against the JPEG max_memory setting. In some systems the above
452 * code would risk an out-of-memory error. However, in general we don't
453 * know the output image dimensions before jpeg_start_decompress(), unless we
454 * call jpeg_calc_output_dimensions(). See libjpeg.txt for more about this.
456 * Scanlines are returned in the same order as they appear in the JPEG file,
457 * which is standardly top-to-bottom. If you must emit data bottom-to-top,
458 * you can use one of the virtual arrays provided by the JPEG memory manager
459 * to invert the data. See wrbmp.c for an example.
461 * As with compression, some operating modes may require temporary files.
462 * On some systems you may need to set up a signal handler to ensure that
463 * temporary files are deleted if the program is interrupted. See libjpeg.txt.