1 /*
2  * example.c
3  *
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.doc.
7  *
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.
10  *
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.
14  */
15 
16 #include <stdio.h>
17 
18 /*
19  * Include file for users of JPEG library.
20  * You will need to have included system headers that define at least
21  * the typedefs FILE and size_t before you can include jpeglib.h.
22  * (stdio.h is sufficient on ANSI-conforming systems.)
23  * You may also wish to include "jerror.h".
24  */
25 
26 #include "jpeglib.h"
27 
28 /*
29  * <setjmp.h> is used for the optional error recovery mechanism shown in
30  * the second part of the example.
31  */
32 
33 #include <setjmp.h>
34 
35 
36 
37 /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
38 
39 /* This half of the example shows how to feed data into the JPEG compressor.
40  * We present a minimal version that does not worry about refinements such
41  * as error recovery (the JPEG code will just exit() if it gets an error).
42  */
43 
44 
45 /*
46  * IMAGE DATA FORMATS:
47  *
48  * The standard input image format is a rectangular array of pixels, with
49  * each pixel having the same number of "component" values (color channels).
50  * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
51  * If you are working with color data, then the color values for each pixel
52  * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
53  * RGB color.
54  *
55  * For this example, we'll assume that this data structure matches the way
56  * our application has stored the image in memory, so we can just pass a
57  * pointer to our image buffer.  In particular, let's say that the image is
58  * RGB color and is described by:
59  */
60 
61 extern JSAMPLE * image_buffer;	/* Points to large array of R,G,B-order data */
62 extern int image_height;	/* Number of rows in image */
63 extern int image_width;		/* Number of columns in image */
64 
65 
66 /*
67  * Sample routine for JPEG compression.  We assume that the target file name
68  * and a compression quality factor are passed in.
69  */
70 
71 GLOBAL void
write_JPEG_file(char * filename,int quality)72 write_JPEG_file (char * filename, int quality)
73 {
74   /* This struct contains the JPEG compression parameters and pointers to
75    * working space (which is allocated as needed by the JPEG library).
76    * It is possible to have several such structures, representing multiple
77    * compression/decompression processes, in existence at once.  We refer
78    * to any one struct (and its associated working data) as a "JPEG object".
79    */
80   struct jpeg_compress_struct cinfo;
81   /* This struct represents a JPEG error handler.  It is declared separately
82    * because applications often want to supply a specialized error handler
83    * (see the second half of this file for an example).  But here we just
84    * take the easy way out and use the standard error handler, which will
85    * print a message on stderr and call exit() if compression fails.
86    */
87   struct jpeg_error_mgr jerr;
88   /* More stuff */
89   FILE * outfile;		/* target file */
90   JSAMPROW row_pointer[1];	/* pointer to JSAMPLE row[s] */
91   int row_stride;		/* physical row width in image buffer */
92 
93   /* Step 1: allocate and initialize JPEG compression object */
94 
95   /* We have to set up the error handler first, in case the initialization
96    * step fails.  (Unlikely, but it could happen if you are out of memory.)
97    * This routine fills in the contents of struct jerr, and returns jerr's
98    * address which we place into the link field in cinfo.
99    */
100   cinfo.err = jpeg_std_error(&jerr);
101   /* Now we can initialize the JPEG compression object. */
102   jpeg_create_compress(&cinfo);
103 
104   /* Step 2: specify data destination (eg, a file) */
105   /* Note: steps 2 and 3 can be done in either order. */
106 
107   /* Here we use the library-supplied code to send compressed data to a
108    * stdio stream.  You can also write your own code to do something else.
109    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
110    * requires it in order to write binary files.
111    */
112   if ((outfile = fopen(filename, "wb")) == NULL) {
113     fprintf(stderr, "can't open %s\n", filename);
114     exit(1);
115   }
116   jpeg_stdio_dest(&cinfo, outfile);
117 
118   /* Step 3: set parameters for compression */
119 
120   /* First we supply a description of the input image.
121    * Four fields of the cinfo struct must be filled in:
122    */
123   cinfo.image_width = image_width; 	/* image width and height, in pixels */
124   cinfo.image_height = image_height;
125   cinfo.input_components = 3;		/* # of color components per pixel */
126   cinfo.in_color_space = JCS_RGB; 	/* colorspace of input image */
127   /* Now use the library's routine to set default compression parameters.
128    * (You must set at least cinfo.in_color_space before calling this,
129    * since the defaults depend on the source color space.)
130    */
131   jpeg_set_defaults(&cinfo);
132   /* Now you can set any non-default parameters you wish to.
133    * Here we just illustrate the use of quality (quantization table) scaling:
134    */
135   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
136 
137   /* Step 4: Start compressor */
138 
139   /* TRUE ensures that we will write a complete interchange-JPEG file.
140    * Pass TRUE unless you are very sure of what you're doing.
141    */
142   jpeg_start_compress(&cinfo, TRUE);
143 
144   /* Step 5: while (scan lines remain to be written) */
145   /*           jpeg_write_scanlines(...); */
146 
147   /* Here we use the library's state variable cinfo.next_scanline as the
148    * loop counter, so that we don't have to keep track ourselves.
149    * To keep things simple, we pass one scanline per call; you can pass
150    * more if you wish, though.
151    */
152   row_stride = image_width * 3;	/* JSAMPLEs per row in image_buffer */
153 
154   while (cinfo.next_scanline < cinfo.image_height) {
155     row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
156     (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
157   }
158 
159   /* Step 6: Finish compression */
160 
161   jpeg_finish_compress(&cinfo);
162   /* After finish_compress, we can close the output file. */
163   fclose(outfile);
164 
165   /* Step 7: release JPEG compression object */
166 
167   /* This is an important step since it will release a good deal of memory. */
168   jpeg_destroy_compress(&cinfo);
169 
170   /* And we're done! */
171 }
172 
173 
174 /*
175  * SOME FINE POINTS:
176  *
177  * In the above loop, we ignored the return value of jpeg_write_scanlines,
178  * which is the number of scanlines actually written.  We could get away
179  * with this because we were only relying on the value of cinfo.next_scanline,
180  * which will be incremented correctly.  If you maintain additional loop
181  * variables then you should be careful to increment them properly.
182  * Actually, for output to a stdio stream you needn't worry, because
183  * then jpeg_write_scanlines will write all the lines passed (or else exit
184  * with a fatal error).  Partial writes can only occur if you use a data
185  * destination module that can demand suspension of the compressor.
186  * (If you don't know what that's for, you don't need it.)
187  *
188  * If the compressor requires full-image buffers (for entropy-coding
189  * optimization or a noninterleaved JPEG file), it will create temporary
190  * files for anything that doesn't fit within the maximum-memory setting.
191  * (Note that temp files are NOT needed if you use the default parameters.)
192  * On some systems you may need to set up a signal handler to ensure that
193  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
194  *
195  * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
196  * files to be compatible with everyone else's.  If you cannot readily read
197  * your data in that order, you'll need an intermediate array to hold the
198  * image.  See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
199  * source data using the JPEG code's internal virtual-array mechanisms.
200  */
201 
202 
203 
204 /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
205 
206 /* This half of the example shows how to read data from the JPEG decompressor.
207  * It's a bit more refined than the above, in that we show:
208  *   (a) how to modify the JPEG library's standard error-reporting behavior;
209  *   (b) how to allocate workspace using the library's memory manager.
210  *
211  * Just to make this example a little different from the first one, we'll
212  * assume that we do not intend to put the whole image into an in-memory
213  * buffer, but to send it line-by-line someplace else.  We need a one-
214  * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
215  * memory manager allocate it for us.  This approach is actually quite useful
216  * because we don't need to remember to deallocate the buffer separately: it
217  * will go away automatically when the JPEG object is cleaned up.
218  */
219 
220 
221 /*
222  * ERROR HANDLING:
223  *
224  * The JPEG library's standard error handler (jerror.c) is divided into
225  * several "methods" which you can override individually.  This lets you
226  * adjust the behavior without duplicating a lot of code, which you might
227  * have to update with each future release.
228  *
229  * Our example here shows how to override the "error_exit" method so that
230  * control is returned to the library's caller when a fatal error occurs,
231  * rather than calling exit() as the standard error_exit method does.
232  *
233  * We use C's setjmp/longjmp facility to return control.  This means that the
234  * routine which calls the JPEG library must first execute a setjmp() call to
235  * establish the return point.  We want the replacement error_exit to do a
236  * longjmp().  But we need to make the setjmp buffer accessible to the
237  * error_exit routine.  To do this, we make a private extension of the
238  * standard JPEG error handler object.  (If we were using C++, we'd say we
239  * were making a subclass of the regular error handler.)
240  *
241  * Here's the extended error handler struct:
242  */
243 
244 struct my_error_mgr {
245   struct jpeg_error_mgr pub;	/* "public" fields */
246 
247   jmp_buf setjmp_buffer;	/* for return to caller */
248 };
249 
250 typedef struct my_error_mgr * my_error_ptr;
251 
252 /*
253  * Here's the routine that will replace the standard error_exit method:
254  */
255 
256 METHODDEF void
my_error_exit(j_common_ptr cinfo)257 my_error_exit (j_common_ptr cinfo)
258 {
259   /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
260   my_error_ptr myerr = (my_error_ptr) cinfo->err;
261 
262   /* Always display the message. */
263   /* We could postpone this until after returning, if we chose. */
264   (*cinfo->err->output_message) (cinfo);
265 
266   /* Return control to the setjmp point */
267   longjmp(myerr->setjmp_buffer, 1);
268 }
269 
270 
271 /*
272  * Sample routine for JPEG decompression.  We assume that the source file name
273  * is passed in.  We want to return 1 on success, 0 on error.
274  */
275 
276 
277 GLOBAL int
read_JPEG_file(char * filename)278 read_JPEG_file (char * filename)
279 {
280   /* This struct contains the JPEG decompression parameters and pointers to
281    * working space (which is allocated as needed by the JPEG library).
282    */
283   struct jpeg_decompress_struct cinfo;
284   /* We use our private extension JPEG error handler. */
285   struct my_error_mgr jerr;
286   /* More stuff */
287   FILE * infile;		/* source file */
288   JSAMPARRAY buffer;		/* Output row buffer */
289   int row_stride;		/* physical row width in output buffer */
290 
291   /* In this example we want to open the input file before doing anything else,
292    * so that the setjmp() error recovery below can assume the file is open.
293    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
294    * requires it in order to read binary files.
295    */
296 
297   if ((infile = fopen(filename, "rb")) == NULL) {
298     fprintf(stderr, "can't open %s\n", filename);
299     return 0;
300   }
301 
302   /* Step 1: allocate and initialize JPEG decompression object */
303 
304   /* We set up the normal JPEG error routines, then override error_exit. */
305   cinfo.err = jpeg_std_error(&jerr.pub);
306   jerr.pub.error_exit = my_error_exit;
307   /* Establish the setjmp return context for my_error_exit to use. */
308   if (setjmp(jerr.setjmp_buffer)) {
309     /* If we get here, the JPEG code has signaled an error.
310      * We need to clean up the JPEG object, close the input file, and return.
311      */
312     jpeg_destroy_decompress(&cinfo);
313     fclose(infile);
314     return 0;
315   }
316   /* Now we can initialize the JPEG decompression object. */
317   jpeg_create_decompress(&cinfo);
318 
319   /* Step 2: specify data source (eg, a file) */
320 
321   jpeg_stdio_src(&cinfo, infile);
322 
323   /* Step 3: read file parameters with jpeg_read_header() */
324 
325   (void) jpeg_read_header(&cinfo, TRUE);
326   /* We can ignore the return value from jpeg_read_header since
327    *   (a) suspension is not possible with the stdio data source, and
328    *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
329    * See libjpeg.doc for more info.
330    */
331 
332   /* Step 4: set parameters for decompression */
333 
334   /* In this example, we don't need to change any of the defaults set by
335    * jpeg_read_header(), so we do nothing here.
336    */
337 
338   /* Step 5: Start decompressor */
339 
340   jpeg_start_decompress(&cinfo);
341 
342   /* We may need to do some setup of our own at this point before reading
343    * the data.  After jpeg_start_decompress() we have the correct scaled
344    * output image dimensions available, as well as the output colormap
345    * if we asked for color quantization.
346    * In this example, we need to make an output work buffer of the right size.
347    */
348   /* JSAMPLEs per row in output buffer */
349   row_stride = cinfo.output_width * cinfo.output_components;
350   /* Make a one-row-high sample array that will go away when done with image */
351   buffer = (*cinfo.mem->alloc_sarray)
352 		((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
353 
354   /* Step 6: while (scan lines remain to be read) */
355   /*           jpeg_read_scanlines(...); */
356 
357   /* Here we use the library's state variable cinfo.output_scanline as the
358    * loop counter, so that we don't have to keep track ourselves.
359    */
360   while (cinfo.output_scanline < cinfo.output_height) {
361     (void) jpeg_read_scanlines(&cinfo, buffer, 1);
362     /* Assume put_scanline_someplace wants a pointer and sample count. */
363     put_scanline_someplace(buffer[0], row_stride);
364   }
365 
366   /* Step 7: Finish decompression */
367 
368   (void) jpeg_finish_decompress(&cinfo);
369   /* We can ignore the return value since suspension is not possible
370    * with the stdio data source.
371    */
372 
373   /* Step 8: Release JPEG decompression object */
374 
375   /* This is an important step since it will release a good deal of memory. */
376   jpeg_destroy_decompress(&cinfo);
377 
378   /* After finish_decompress, we can close the input file.
379    * Here we postpone it until after no more JPEG errors are possible,
380    * so as to simplify the setjmp error logic above.  (Actually, I don't
381    * think that jpeg_destroy can do an error exit, but why assume anything...)
382    */
383   fclose(infile);
384 
385   /* At this point you may want to check to see whether any corrupt-data
386    * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
387    */
388 
389   /* And we're done! */
390   return 1;
391 }
392 
393 
394 /*
395  * SOME FINE POINTS:
396  *
397  * In the above code, we ignored the return value of jpeg_read_scanlines,
398  * which is the number of scanlines actually read.  We could get away with
399  * this because we asked for only one line at a time and we weren't using
400  * a suspending data source.  See libjpeg.doc for more info.
401  *
402  * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
403  * we should have done it beforehand to ensure that the space would be
404  * counted against the JPEG max_memory setting.  In some systems the above
405  * code would risk an out-of-memory error.  However, in general we don't
406  * know the output image dimensions before jpeg_start_decompress(), unless we
407  * call jpeg_calc_output_dimensions().  See libjpeg.doc for more about this.
408  *
409  * Scanlines are returned in the same order as they appear in the JPEG file,
410  * which is standardly top-to-bottom.  If you must emit data bottom-to-top,
411  * you can use one of the virtual arrays provided by the JPEG memory manager
412  * to invert the data.  See wrbmp.c for an example.
413  *
414  * As with compression, some operating modes may require temporary files.
415  * On some systems you may need to set up a signal handler to ensure that
416  * temporary files are deleted if the program is interrupted.  See libjpeg.doc.
417  */
418