Home | History | Annotate | Download | only in libjpeg-turbo
      1 /*
      2  * example.txt
      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.txt.
      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 /* 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.
     28  */
     29 
     30 #include <stdio.h>
     31 
     32 /*
     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".
     38  */
     39 
     40 #include "jpeglib.h"
     41 
     42 /*
     43  * <setjmp.h> is used for the optional error recovery mechanism shown in
     44  * the second part of the example.
     45  */
     46 
     47 #include <setjmp.h>
     48 
     49 
     50 
     51 /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
     52 
     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).
     56  */
     57 
     58 
     59 /*
     60  * IMAGE DATA FORMATS:
     61  *
     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
     67  * RGB color.
     68  *
     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:
     73  */
     74 
     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 */
     78 
     79 
     80 /*
     81  * Sample routine for JPEG compression.  We assume that the target file name
     82  * and a compression quality factor are passed in.
     83  */
     84 
     85 GLOBAL(void)
     86 write_JPEG_file(char *filename, int quality)
     87 {
     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".
     93    */
     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.
    102    */
    103   struct jpeg_error_mgr jerr;
    104   /* More stuff */
    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 */
    108 
    109   /* Step 1: allocate and initialize JPEG compression object */
    110 
    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.
    115    */
    116   cinfo.err = jpeg_std_error(&jerr);
    117   /* Now we can initialize the JPEG compression object. */
    118   jpeg_create_compress(&cinfo);
    119 
    120   /* Step 2: specify data destination (eg, a file) */
    121   /* Note: steps 2 and 3 can be done in either order. */
    122 
    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.
    127    */
    128   if ((outfile = fopen(filename, "wb")) == NULL) {
    129     fprintf(stderr, "can't open %s\n", filename);
    130     exit(1);
    131   }
    132   jpeg_stdio_dest(&cinfo, outfile);
    133 
    134   /* Step 3: set parameters for compression */
    135 
    136   /* First we supply a description of the input image.
    137    * Four fields of the cinfo struct must be filled in:
    138    */
    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.)
    146    */
    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:
    150    */
    151   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
    152 
    153   /* Step 4: Start compressor */
    154 
    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.
    157    */
    158   jpeg_start_compress(&cinfo, TRUE);
    159 
    160   /* Step 5: while (scan lines remain to be written) */
    161   /*           jpeg_write_scanlines(...); */
    162 
    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.
    167    */
    168   row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */
    169 
    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.
    174      */
    175     row_pointer[0] = &image_buffer[cinfo.next_scanline * row_stride];
    176     (void)jpeg_write_scanlines(&cinfo, row_pointer, 1);
    177   }
    178 
    179   /* Step 6: Finish compression */
    180 
    181   jpeg_finish_compress(&cinfo);
    182   /* After finish_compress, we can close the output file. */
    183   fclose(outfile);
    184 
    185   /* Step 7: release JPEG compression object */
    186 
    187   /* This is an important step since it will release a good deal of memory. */
    188   jpeg_destroy_compress(&cinfo);
    189 
    190   /* And we're done! */
    191 }
    192 
    193 
    194 /*
    195  * SOME FINE POINTS:
    196  *
    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.)
    207  *
    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.
    214  *
    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.
    220  */
    221 
    222 
    223 
    224 /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
    225 
    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.
    230  *
    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.
    238  */
    239 
    240 
    241 /*
    242  * ERROR HANDLING:
    243  *
    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.
    248  *
    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.
    252  *
    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.)
    260  *
    261  * Here's the extended error handler struct:
    262  */
    263 
    264 struct my_error_mgr {
    265   struct jpeg_error_mgr pub;    /* "public" fields */
    266 
    267   jmp_buf setjmp_buffer;        /* for return to caller */
    268 };
    269 
    270 typedef struct my_error_mgr *my_error_ptr;
    271 
    272 /*
    273  * Here's the routine that will replace the standard error_exit method:
    274  */
    275 
    276 METHODDEF(void)
    277 my_error_exit(j_common_ptr cinfo)
    278 {
    279   /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
    280   my_error_ptr myerr = (my_error_ptr)cinfo->err;
    281 
    282   /* Always display the message. */
    283   /* We could postpone this until after returning, if we chose. */
    284   (*cinfo->err->output_message) (cinfo);
    285 
    286   /* Return control to the setjmp point */
    287   longjmp(myerr->setjmp_buffer, 1);
    288 }
    289 
    290 
    291 /*
    292  * Sample routine for JPEG decompression.  We assume that the source file name
    293  * is passed in.  We want to return 1 on success, 0 on error.
    294  */
    295 
    296 
    297 GLOBAL(int)
    298 read_JPEG_file(char *filename)
    299 {
    300   /* This struct contains the JPEG decompression parameters and pointers to
    301    * working space (which is allocated as needed by the JPEG library).
    302    */
    303   struct jpeg_decompress_struct cinfo;
    304   /* We use our private extension JPEG error handler.
    305    * Note that this struct must live as long as the main JPEG parameter
    306    * struct, to avoid dangling-pointer problems.
    307    */
    308   struct my_error_mgr jerr;
    309   /* More stuff */
    310   FILE *infile;                 /* source file */
    311   JSAMPARRAY buffer;            /* Output row buffer */
    312   int row_stride;               /* physical row width in output buffer */
    313 
    314   /* In this example we want to open the input file before doing anything else,
    315    * so that the setjmp() error recovery below can assume the file is open.
    316    * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
    317    * requires it in order to read binary files.
    318    */
    319 
    320   if ((infile = fopen(filename, "rb")) == NULL) {
    321     fprintf(stderr, "can't open %s\n", filename);
    322     return 0;
    323   }
    324 
    325   /* Step 1: allocate and initialize JPEG decompression object */
    326 
    327   /* We set up the normal JPEG error routines, then override error_exit. */
    328   cinfo.err = jpeg_std_error(&jerr.pub);
    329   jerr.pub.error_exit = my_error_exit;
    330   /* Establish the setjmp return context for my_error_exit to use. */
    331   if (setjmp(jerr.setjmp_buffer)) {
    332     /* If we get here, the JPEG code has signaled an error.
    333      * We need to clean up the JPEG object, close the input file, and return.
    334      */
    335     jpeg_destroy_decompress(&cinfo);
    336     fclose(infile);
    337     return 0;
    338   }
    339   /* Now we can initialize the JPEG decompression object. */
    340   jpeg_create_decompress(&cinfo);
    341 
    342   /* Step 2: specify data source (eg, a file) */
    343 
    344   jpeg_stdio_src(&cinfo, infile);
    345 
    346   /* Step 3: read file parameters with jpeg_read_header() */
    347 
    348   (void)jpeg_read_header(&cinfo, TRUE);
    349   /* We can ignore the return value from jpeg_read_header since
    350    *   (a) suspension is not possible with the stdio data source, and
    351    *   (b) we passed TRUE to reject a tables-only JPEG file as an error.
    352    * See libjpeg.txt for more info.
    353    */
    354 
    355   /* Step 4: set parameters for decompression */
    356 
    357   /* In this example, we don't need to change any of the defaults set by
    358    * jpeg_read_header(), so we do nothing here.
    359    */
    360 
    361   /* Step 5: Start decompressor */
    362 
    363   (void)jpeg_start_decompress(&cinfo);
    364   /* We can ignore the return value since suspension is not possible
    365    * with the stdio data source.
    366    */
    367 
    368   /* We may need to do some setup of our own at this point before reading
    369    * the data.  After jpeg_start_decompress() we have the correct scaled
    370    * output image dimensions available, as well as the output colormap
    371    * if we asked for color quantization.
    372    * In this example, we need to make an output work buffer of the right size.
    373    */
    374   /* JSAMPLEs per row in output buffer */
    375   row_stride = cinfo.output_width * cinfo.output_components;
    376   /* Make a one-row-high sample array that will go away when done with image */
    377   buffer = (*cinfo.mem->alloc_sarray)
    378                 ((j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1);
    379 
    380   /* Step 6: while (scan lines remain to be read) */
    381   /*           jpeg_read_scanlines(...); */
    382 
    383   /* Here we use the library's state variable cinfo.output_scanline as the
    384    * loop counter, so that we don't have to keep track ourselves.
    385    */
    386   while (cinfo.output_scanline < cinfo.output_height) {
    387     /* jpeg_read_scanlines expects an array of pointers to scanlines.
    388      * Here the array is only one element long, but you could ask for
    389      * more than one scanline at a time if that's more convenient.
    390      */
    391     (void)jpeg_read_scanlines(&cinfo, buffer, 1);
    392     /* Assume put_scanline_someplace wants a pointer and sample count. */
    393     put_scanline_someplace(buffer[0], row_stride);
    394   }
    395 
    396   /* Step 7: Finish decompression */
    397 
    398   (void)jpeg_finish_decompress(&cinfo);
    399   /* We can ignore the return value since suspension is not possible
    400    * with the stdio data source.
    401    */
    402 
    403   /* Step 8: Release JPEG decompression object */
    404 
    405   /* This is an important step since it will release a good deal of memory. */
    406   jpeg_destroy_decompress(&cinfo);
    407 
    408   /* After finish_decompress, we can close the input file.
    409    * Here we postpone it until after no more JPEG errors are possible,
    410    * so as to simplify the setjmp error logic above.  (Actually, I don't
    411    * think that jpeg_destroy can do an error exit, but why assume anything...)
    412    */
    413   fclose(infile);
    414 
    415   /* At this point you may want to check to see whether any corrupt-data
    416    * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
    417    */
    418 
    419   /* And we're done! */
    420   return 1;
    421 }
    422 
    423 
    424 /*
    425  * SOME FINE POINTS:
    426  *
    427  * In the above code, we ignored the return value of jpeg_read_scanlines,
    428  * which is the number of scanlines actually read.  We could get away with
    429  * this because we asked for only one line at a time and we weren't using
    430  * a suspending data source.  See libjpeg.txt for more info.
    431  *
    432  * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
    433  * we should have done it beforehand to ensure that the space would be
    434  * counted against the JPEG max_memory setting.  In some systems the above
    435  * code would risk an out-of-memory error.  However, in general we don't
    436  * know the output image dimensions before jpeg_start_decompress(), unless we
    437  * call jpeg_calc_output_dimensions().  See libjpeg.txt for more about this.
    438  *
    439  * Scanlines are returned in the same order as they appear in the JPEG file,
    440  * which is standardly top-to-bottom.  If you must emit data bottom-to-top,
    441  * you can use one of the virtual arrays provided by the JPEG memory manager
    442  * to invert the data.  See wrbmp.c for an example.
    443  *
    444  * As with compression, some operating modes may require temporary files.
    445  * On some systems you may need to set up a signal handler to ensure that
    446  * temporary files are deleted if the program is interrupted.  See libjpeg.txt.
    447  */
    448