/src/FreeImage/Source/LibJPEG/libjpeg.txt
Plain Text | 3085 lines | 2576 code | 509 blank | 0 comment | 0 complexity | 38da6f995510b093dc35a44e292db67a MD5 | raw file
Large files files are truncated, but you can click here to view the full file
1USING THE IJG JPEG LIBRARY 2 3Copyright (C) 1994-2011, Thomas G. Lane, Guido Vollbeding. 4This file is part of the Independent JPEG Group's software. 5For conditions of distribution and use, see the accompanying README file. 6 7 8This file describes how to use the IJG JPEG library within an application 9program. Read it if you want to write a program that uses the library. 10 11The file example.c provides heavily commented skeleton code for calling the 12JPEG library. Also see jpeglib.h (the include file to be used by application 13programs) for full details about data structures and function parameter lists. 14The library source code, of course, is the ultimate reference. 15 16Note that there have been *major* changes from the application interface 17presented by IJG version 4 and earlier versions. The old design had several 18inherent limitations, and it had accumulated a lot of cruft as we added 19features while trying to minimize application-interface changes. We have 20sacrificed backward compatibility in the version 5 rewrite, but we think the 21improvements justify this. 22 23 24TABLE OF CONTENTS 25----------------- 26 27Overview: 28 Functions provided by the library 29 Outline of typical usage 30Basic library usage: 31 Data formats 32 Compression details 33 Decompression details 34 Mechanics of usage: include files, linking, etc 35Advanced features: 36 Compression parameter selection 37 Decompression parameter selection 38 Special color spaces 39 Error handling 40 Compressed data handling (source and destination managers) 41 I/O suspension 42 Progressive JPEG support 43 Buffered-image mode 44 Abbreviated datastreams and multiple images 45 Special markers 46 Raw (downsampled) image data 47 Really raw data: DCT coefficients 48 Progress monitoring 49 Memory management 50 Memory usage 51 Library compile-time options 52 Portability considerations 53 Notes for MS-DOS implementors 54 55You should read at least the overview and basic usage sections before trying 56to program with the library. The sections on advanced features can be read 57if and when you need them. 58 59 60OVERVIEW 61======== 62 63Functions provided by the library 64--------------------------------- 65 66The IJG JPEG library provides C code to read and write JPEG-compressed image 67files. The surrounding application program receives or supplies image data a 68scanline at a time, using a straightforward uncompressed image format. All 69details of color conversion and other preprocessing/postprocessing can be 70handled by the library. 71 72The library includes a substantial amount of code that is not covered by the 73JPEG standard but is necessary for typical applications of JPEG. These 74functions preprocess the image before JPEG compression or postprocess it after 75decompression. They include colorspace conversion, downsampling/upsampling, 76and color quantization. The application indirectly selects use of this code 77by specifying the format in which it wishes to supply or receive image data. 78For example, if colormapped output is requested, then the decompression 79library automatically invokes color quantization. 80 81A wide range of quality vs. speed tradeoffs are possible in JPEG processing, 82and even more so in decompression postprocessing. The decompression library 83provides multiple implementations that cover most of the useful tradeoffs, 84ranging from very-high-quality down to fast-preview operation. On the 85compression side we have generally not provided low-quality choices, since 86compression is normally less time-critical. It should be understood that the 87low-quality modes may not meet the JPEG standard's accuracy requirements; 88nonetheless, they are useful for viewers. 89 90A word about functions *not* provided by the library. We handle a subset of 91the ISO JPEG standard; most baseline, extended-sequential, and progressive 92JPEG processes are supported. (Our subset includes all features now in common 93use.) Unsupported ISO options include: 94 * Hierarchical storage 95 * Lossless JPEG 96 * DNL marker 97 * Nonintegral subsampling ratios 98We support both 8- and 12-bit data precision, but this is a compile-time 99choice rather than a run-time choice; hence it is difficult to use both 100precisions in a single application. 101 102By itself, the library handles only interchange JPEG datastreams --- in 103particular the widely used JFIF file format. The library can be used by 104surrounding code to process interchange or abbreviated JPEG datastreams that 105are embedded in more complex file formats. (For example, this library is 106used by the free LIBTIFF library to support JPEG compression in TIFF.) 107 108 109Outline of typical usage 110------------------------ 111 112The rough outline of a JPEG compression operation is: 113 114 Allocate and initialize a JPEG compression object 115 Specify the destination for the compressed data (eg, a file) 116 Set parameters for compression, including image size & colorspace 117 jpeg_start_compress(...); 118 while (scan lines remain to be written) 119 jpeg_write_scanlines(...); 120 jpeg_finish_compress(...); 121 Release the JPEG compression object 122 123A JPEG compression object holds parameters and working state for the JPEG 124library. We make creation/destruction of the object separate from starting 125or finishing compression of an image; the same object can be re-used for a 126series of image compression operations. This makes it easy to re-use the 127same parameter settings for a sequence of images. Re-use of a JPEG object 128also has important implications for processing abbreviated JPEG datastreams, 129as discussed later. 130 131The image data to be compressed is supplied to jpeg_write_scanlines() from 132in-memory buffers. If the application is doing file-to-file compression, 133reading image data from the source file is the application's responsibility. 134The library emits compressed data by calling a "data destination manager", 135which typically will write the data into a file; but the application can 136provide its own destination manager to do something else. 137 138Similarly, the rough outline of a JPEG decompression operation is: 139 140 Allocate and initialize a JPEG decompression object 141 Specify the source of the compressed data (eg, a file) 142 Call jpeg_read_header() to obtain image info 143 Set parameters for decompression 144 jpeg_start_decompress(...); 145 while (scan lines remain to be read) 146 jpeg_read_scanlines(...); 147 jpeg_finish_decompress(...); 148 Release the JPEG decompression object 149 150This is comparable to the compression outline except that reading the 151datastream header is a separate step. This is helpful because information 152about the image's size, colorspace, etc is available when the application 153selects decompression parameters. For example, the application can choose an 154output scaling ratio that will fit the image into the available screen size. 155 156The decompression library obtains compressed data by calling a data source 157manager, which typically will read the data from a file; but other behaviors 158can be obtained with a custom source manager. Decompressed data is delivered 159into in-memory buffers passed to jpeg_read_scanlines(). 160 161It is possible to abort an incomplete compression or decompression operation 162by calling jpeg_abort(); or, if you do not need to retain the JPEG object, 163simply release it by calling jpeg_destroy(). 164 165JPEG compression and decompression objects are two separate struct types. 166However, they share some common fields, and certain routines such as 167jpeg_destroy() can work on either type of object. 168 169The JPEG library has no static variables: all state is in the compression 170or decompression object. Therefore it is possible to process multiple 171compression and decompression operations concurrently, using multiple JPEG 172objects. 173 174Both compression and decompression can be done in an incremental memory-to- 175memory fashion, if suitable source/destination managers are used. See the 176section on "I/O suspension" for more details. 177 178 179BASIC LIBRARY USAGE 180=================== 181 182Data formats 183------------ 184 185Before diving into procedural details, it is helpful to understand the 186image data format that the JPEG library expects or returns. 187 188The standard input image format is a rectangular array of pixels, with each 189pixel having the same number of "component" or "sample" values (color 190channels). You must specify how many components there are and the colorspace 191interpretation of the components. Most applications will use RGB data 192(three components per pixel) or grayscale data (one component per pixel). 193PLEASE NOTE THAT RGB DATA IS THREE SAMPLES PER PIXEL, GRAYSCALE ONLY ONE. 194A remarkable number of people manage to miss this, only to find that their 195programs don't work with grayscale JPEG files. 196 197There is no provision for colormapped input. JPEG files are always full-color 198or full grayscale (or sometimes another colorspace such as CMYK). You can 199feed in a colormapped image by expanding it to full-color format. However 200JPEG often doesn't work very well with source data that has been colormapped, 201because of dithering noise. This is discussed in more detail in the JPEG FAQ 202and the other references mentioned in the README file. 203 204Pixels are stored by scanlines, with each scanline running from left to 205right. The component values for each pixel are adjacent in the row; for 206example, R,G,B,R,G,B,R,G,B,... for 24-bit RGB color. Each scanline is an 207array of data type JSAMPLE --- which is typically "unsigned char", unless 208you've changed jmorecfg.h. (You can also change the RGB pixel layout, say 209to B,G,R order, by modifying jmorecfg.h. But see the restrictions listed in 210that file before doing so.) 211 212A 2-D array of pixels is formed by making a list of pointers to the starts of 213scanlines; so the scanlines need not be physically adjacent in memory. Even 214if you process just one scanline at a time, you must make a one-element 215pointer array to conform to this structure. Pointers to JSAMPLE rows are of 216type JSAMPROW, and the pointer to the pointer array is of type JSAMPARRAY. 217 218The library accepts or supplies one or more complete scanlines per call. 219It is not possible to process part of a row at a time. Scanlines are always 220processed top-to-bottom. You can process an entire image in one call if you 221have it all in memory, but usually it's simplest to process one scanline at 222a time. 223 224For best results, source data values should have the precision specified by 225BITS_IN_JSAMPLE (normally 8 bits). For instance, if you choose to compress 226data that's only 6 bits/channel, you should left-justify each value in a 227byte before passing it to the compressor. If you need to compress data 228that has more than 8 bits/channel, compile with BITS_IN_JSAMPLE = 12. 229(See "Library compile-time options", later.) 230 231 232The data format returned by the decompressor is the same in all details, 233except that colormapped output is supported. (Again, a JPEG file is never 234colormapped. But you can ask the decompressor to perform on-the-fly color 235quantization to deliver colormapped output.) If you request colormapped 236output then the returned data array contains a single JSAMPLE per pixel; 237its value is an index into a color map. The color map is represented as 238a 2-D JSAMPARRAY in which each row holds the values of one color component, 239that is, colormap[i][j] is the value of the i'th color component for pixel 240value (map index) j. Note that since the colormap indexes are stored in 241JSAMPLEs, the maximum number of colors is limited by the size of JSAMPLE 242(ie, at most 256 colors for an 8-bit JPEG library). 243 244 245Compression details 246------------------- 247 248Here we revisit the JPEG compression outline given in the overview. 249 2501. Allocate and initialize a JPEG compression object. 251 252A JPEG compression object is a "struct jpeg_compress_struct". (It also has 253a bunch of subsidiary structures which are allocated via malloc(), but the 254application doesn't control those directly.) This struct can be just a local 255variable in the calling routine, if a single routine is going to execute the 256whole JPEG compression sequence. Otherwise it can be static or allocated 257from malloc(). 258 259You will also need a structure representing a JPEG error handler. The part 260of this that the library cares about is a "struct jpeg_error_mgr". If you 261are providing your own error handler, you'll typically want to embed the 262jpeg_error_mgr struct in a larger structure; this is discussed later under 263"Error handling". For now we'll assume you are just using the default error 264handler. The default error handler will print JPEG error/warning messages 265on stderr, and it will call exit() if a fatal error occurs. 266 267You must initialize the error handler structure, store a pointer to it into 268the JPEG object's "err" field, and then call jpeg_create_compress() to 269initialize the rest of the JPEG object. 270 271Typical code for this step, if you are using the default error handler, is 272 273 struct jpeg_compress_struct cinfo; 274 struct jpeg_error_mgr jerr; 275 ... 276 cinfo.err = jpeg_std_error(&jerr); 277 jpeg_create_compress(&cinfo); 278 279jpeg_create_compress allocates a small amount of memory, so it could fail 280if you are out of memory. In that case it will exit via the error handler; 281that's why the error handler must be initialized first. 282 283 2842. Specify the destination for the compressed data (eg, a file). 285 286As previously mentioned, the JPEG library delivers compressed data to a 287"data destination" module. The library includes one data destination 288module which knows how to write to a stdio stream. You can use your own 289destination module if you want to do something else, as discussed later. 290 291If you use the standard destination module, you must open the target stdio 292stream beforehand. Typical code for this step looks like: 293 294 FILE * outfile; 295 ... 296 if ((outfile = fopen(filename, "wb")) == NULL) { 297 fprintf(stderr, "can't open %s\n", filename); 298 exit(1); 299 } 300 jpeg_stdio_dest(&cinfo, outfile); 301 302where the last line invokes the standard destination module. 303 304WARNING: it is critical that the binary compressed data be delivered to the 305output file unchanged. On non-Unix systems the stdio library may perform 306newline translation or otherwise corrupt binary data. To suppress this 307behavior, you may need to use a "b" option to fopen (as shown above), or use 308setmode() or another routine to put the stdio stream in binary mode. See 309cjpeg.c and djpeg.c for code that has been found to work on many systems. 310 311You can select the data destination after setting other parameters (step 3), 312if that's more convenient. You may not change the destination between 313calling jpeg_start_compress() and jpeg_finish_compress(). 314 315 3163. Set parameters for compression, including image size & colorspace. 317 318You must supply information about the source image by setting the following 319fields in the JPEG object (cinfo structure): 320 321 image_width Width of image, in pixels 322 image_height Height of image, in pixels 323 input_components Number of color channels (samples per pixel) 324 in_color_space Color space of source image 325 326The image dimensions are, hopefully, obvious. JPEG supports image dimensions 327of 1 to 64K pixels in either direction. The input color space is typically 328RGB or grayscale, and input_components is 3 or 1 accordingly. (See "Special 329color spaces", later, for more info.) The in_color_space field must be 330assigned one of the J_COLOR_SPACE enum constants, typically JCS_RGB or 331JCS_GRAYSCALE. 332 333JPEG has a large number of compression parameters that determine how the 334image is encoded. Most applications don't need or want to know about all 335these parameters. You can set all the parameters to reasonable defaults by 336calling jpeg_set_defaults(); then, if there are particular values you want 337to change, you can do so after that. The "Compression parameter selection" 338section tells about all the parameters. 339 340You must set in_color_space correctly before calling jpeg_set_defaults(), 341because the defaults depend on the source image colorspace. However the 342other three source image parameters need not be valid until you call 343jpeg_start_compress(). There's no harm in calling jpeg_set_defaults() more 344than once, if that happens to be convenient. 345 346Typical code for a 24-bit RGB source image is 347 348 cinfo.image_width = Width; /* image width and height, in pixels */ 349 cinfo.image_height = Height; 350 cinfo.input_components = 3; /* # of color components per pixel */ 351 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */ 352 353 jpeg_set_defaults(&cinfo); 354 /* Make optional parameter settings here */ 355 356 3574. jpeg_start_compress(...); 358 359After you have established the data destination and set all the necessary 360source image info and other parameters, call jpeg_start_compress() to begin 361a compression cycle. This will initialize internal state, allocate working 362storage, and emit the first few bytes of the JPEG datastream header. 363 364Typical code: 365 366 jpeg_start_compress(&cinfo, TRUE); 367 368The "TRUE" parameter ensures that a complete JPEG interchange datastream 369will be written. This is appropriate in most cases. If you think you might 370want to use an abbreviated datastream, read the section on abbreviated 371datastreams, below. 372 373Once you have called jpeg_start_compress(), you may not alter any JPEG 374parameters or other fields of the JPEG object until you have completed 375the compression cycle. 376 377 3785. while (scan lines remain to be written) 379 jpeg_write_scanlines(...); 380 381Now write all the required image data by calling jpeg_write_scanlines() 382one or more times. You can pass one or more scanlines in each call, up 383to the total image height. In most applications it is convenient to pass 384just one or a few scanlines at a time. The expected format for the passed 385data is discussed under "Data formats", above. 386 387Image data should be written in top-to-bottom scanline order. The JPEG spec 388contains some weasel wording about how top and bottom are application-defined 389terms (a curious interpretation of the English language...) but if you want 390your files to be compatible with everyone else's, you WILL use top-to-bottom 391order. If the source data must be read in bottom-to-top order, you can use 392the JPEG library's virtual array mechanism to invert the data efficiently. 393Examples of this can be found in the sample application cjpeg. 394 395The library maintains a count of the number of scanlines written so far 396in the next_scanline field of the JPEG object. Usually you can just use 397this variable as the loop counter, so that the loop test looks like 398"while (cinfo.next_scanline < cinfo.image_height)". 399 400Code for this step depends heavily on the way that you store the source data. 401example.c shows the following code for the case of a full-size 2-D source 402array containing 3-byte RGB pixels: 403 404 JSAMPROW row_pointer[1]; /* pointer to a single row */ 405 int row_stride; /* physical row width in buffer */ 406 407 row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */ 408 409 while (cinfo.next_scanline < cinfo.image_height) { 410 row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride]; 411 jpeg_write_scanlines(&cinfo, row_pointer, 1); 412 } 413 414jpeg_write_scanlines() returns the number of scanlines actually written. 415This will normally be equal to the number passed in, so you can usually 416ignore the return value. It is different in just two cases: 417 * If you try to write more scanlines than the declared image height, 418 the additional scanlines are ignored. 419 * If you use a suspending data destination manager, output buffer overrun 420 will cause the compressor to return before accepting all the passed lines. 421 This feature is discussed under "I/O suspension", below. The normal 422 stdio destination manager will NOT cause this to happen. 423In any case, the return value is the same as the change in the value of 424next_scanline. 425 426 4276. jpeg_finish_compress(...); 428 429After all the image data has been written, call jpeg_finish_compress() to 430complete the compression cycle. This step is ESSENTIAL to ensure that the 431last bufferload of data is written to the data destination. 432jpeg_finish_compress() also releases working memory associated with the JPEG 433object. 434 435Typical code: 436 437 jpeg_finish_compress(&cinfo); 438 439If using the stdio destination manager, don't forget to close the output 440stdio stream (if necessary) afterwards. 441 442If you have requested a multi-pass operating mode, such as Huffman code 443optimization, jpeg_finish_compress() will perform the additional passes using 444data buffered by the first pass. In this case jpeg_finish_compress() may take 445quite a while to complete. With the default compression parameters, this will 446not happen. 447 448It is an error to call jpeg_finish_compress() before writing the necessary 449total number of scanlines. If you wish to abort compression, call 450jpeg_abort() as discussed below. 451 452After completing a compression cycle, you may dispose of the JPEG object 453as discussed next, or you may use it to compress another image. In that case 454return to step 2, 3, or 4 as appropriate. If you do not change the 455destination manager, the new datastream will be written to the same target. 456If you do not change any JPEG parameters, the new datastream will be written 457with the same parameters as before. Note that you can change the input image 458dimensions freely between cycles, but if you change the input colorspace, you 459should call jpeg_set_defaults() to adjust for the new colorspace; and then 460you'll need to repeat all of step 3. 461 462 4637. Release the JPEG compression object. 464 465When you are done with a JPEG compression object, destroy it by calling 466jpeg_destroy_compress(). This will free all subsidiary memory (regardless of 467the previous state of the object). Or you can call jpeg_destroy(), which 468works for either compression or decompression objects --- this may be more 469convenient if you are sharing code between compression and decompression 470cases. (Actually, these routines are equivalent except for the declared type 471of the passed pointer. To avoid gripes from ANSI C compilers, jpeg_destroy() 472should be passed a j_common_ptr.) 473 474If you allocated the jpeg_compress_struct structure from malloc(), freeing 475it is your responsibility --- jpeg_destroy() won't. Ditto for the error 476handler structure. 477 478Typical code: 479 480 jpeg_destroy_compress(&cinfo); 481 482 4838. Aborting. 484 485If you decide to abort a compression cycle before finishing, you can clean up 486in either of two ways: 487 488* If you don't need the JPEG object any more, just call 489 jpeg_destroy_compress() or jpeg_destroy() to release memory. This is 490 legitimate at any point after calling jpeg_create_compress() --- in fact, 491 it's safe even if jpeg_create_compress() fails. 492 493* If you want to re-use the JPEG object, call jpeg_abort_compress(), or call 494 jpeg_abort() which works on both compression and decompression objects. 495 This will return the object to an idle state, releasing any working memory. 496 jpeg_abort() is allowed at any time after successful object creation. 497 498Note that cleaning up the data destination, if required, is your 499responsibility; neither of these routines will call term_destination(). 500(See "Compressed data handling", below, for more about that.) 501 502jpeg_destroy() and jpeg_abort() are the only safe calls to make on a JPEG 503object that has reported an error by calling error_exit (see "Error handling" 504for more info). The internal state of such an object is likely to be out of 505whack. Either of these two routines will return the object to a known state. 506 507 508Decompression details 509--------------------- 510 511Here we revisit the JPEG decompression outline given in the overview. 512 5131. Allocate and initialize a JPEG decompression object. 514 515This is just like initialization for compression, as discussed above, 516except that the object is a "struct jpeg_decompress_struct" and you 517call jpeg_create_decompress(). Error handling is exactly the same. 518 519Typical code: 520 521 struct jpeg_decompress_struct cinfo; 522 struct jpeg_error_mgr jerr; 523 ... 524 cinfo.err = jpeg_std_error(&jerr); 525 jpeg_create_decompress(&cinfo); 526 527(Both here and in the IJG code, we usually use variable name "cinfo" for 528both compression and decompression objects.) 529 530 5312. Specify the source of the compressed data (eg, a file). 532 533As previously mentioned, the JPEG library reads compressed data from a "data 534source" module. The library includes one data source module which knows how 535to read from a stdio stream. You can use your own source module if you want 536to do something else, as discussed later. 537 538If you use the standard source module, you must open the source stdio stream 539beforehand. Typical code for this step looks like: 540 541 FILE * infile; 542 ... 543 if ((infile = fopen(filename, "rb")) == NULL) { 544 fprintf(stderr, "can't open %s\n", filename); 545 exit(1); 546 } 547 jpeg_stdio_src(&cinfo, infile); 548 549where the last line invokes the standard source module. 550 551WARNING: it is critical that the binary compressed data be read unchanged. 552On non-Unix systems the stdio library may perform newline translation or 553otherwise corrupt binary data. To suppress this behavior, you may need to use 554a "b" option to fopen (as shown above), or use setmode() or another routine to 555put the stdio stream in binary mode. See cjpeg.c and djpeg.c for code that 556has been found to work on many systems. 557 558You may not change the data source between calling jpeg_read_header() and 559jpeg_finish_decompress(). If you wish to read a series of JPEG images from 560a single source file, you should repeat the jpeg_read_header() to 561jpeg_finish_decompress() sequence without reinitializing either the JPEG 562object or the data source module; this prevents buffered input data from 563being discarded. 564 565 5663. Call jpeg_read_header() to obtain image info. 567 568Typical code for this step is just 569 570 jpeg_read_header(&cinfo, TRUE); 571 572This will read the source datastream header markers, up to the beginning 573of the compressed data proper. On return, the image dimensions and other 574info have been stored in the JPEG object. The application may wish to 575consult this information before selecting decompression parameters. 576 577More complex code is necessary if 578 * A suspending data source is used --- in that case jpeg_read_header() 579 may return before it has read all the header data. See "I/O suspension", 580 below. The normal stdio source manager will NOT cause this to happen. 581 * Abbreviated JPEG files are to be processed --- see the section on 582 abbreviated datastreams. Standard applications that deal only in 583 interchange JPEG files need not be concerned with this case either. 584 585It is permissible to stop at this point if you just wanted to find out the 586image dimensions and other header info for a JPEG file. In that case, 587call jpeg_destroy() when you are done with the JPEG object, or call 588jpeg_abort() to return it to an idle state before selecting a new data 589source and reading another header. 590 591 5924. Set parameters for decompression. 593 594jpeg_read_header() sets appropriate default decompression parameters based on 595the properties of the image (in particular, its colorspace). However, you 596may well want to alter these defaults before beginning the decompression. 597For example, the default is to produce full color output from a color file. 598If you want colormapped output you must ask for it. Other options allow the 599returned image to be scaled and allow various speed/quality tradeoffs to be 600selected. "Decompression parameter selection", below, gives details. 601 602If the defaults are appropriate, nothing need be done at this step. 603 604Note that all default values are set by each call to jpeg_read_header(). 605If you reuse a decompression object, you cannot expect your parameter 606settings to be preserved across cycles, as you can for compression. 607You must set desired parameter values each time. 608 609 6105. jpeg_start_decompress(...); 611 612Once the parameter values are satisfactory, call jpeg_start_decompress() to 613begin decompression. This will initialize internal state, allocate working 614memory, and prepare for returning data. 615 616Typical code is just 617 618 jpeg_start_decompress(&cinfo); 619 620If you have requested a multi-pass operating mode, such as 2-pass color 621quantization, jpeg_start_decompress() will do everything needed before data 622output can begin. In this case jpeg_start_decompress() may take quite a while 623to complete. With a single-scan (non progressive) JPEG file and default 624decompression parameters, this will not happen; jpeg_start_decompress() will 625return quickly. 626 627After this call, the final output image dimensions, including any requested 628scaling, are available in the JPEG object; so is the selected colormap, if 629colormapped output has been requested. Useful fields include 630 631 output_width image width and height, as scaled 632 output_height 633 out_color_components # of color components in out_color_space 634 output_components # of color components returned per pixel 635 colormap the selected colormap, if any 636 actual_number_of_colors number of entries in colormap 637 638output_components is 1 (a colormap index) when quantizing colors; otherwise it 639equals out_color_components. It is the number of JSAMPLE values that will be 640emitted per pixel in the output arrays. 641 642Typically you will need to allocate data buffers to hold the incoming image. 643You will need output_width * output_components JSAMPLEs per scanline in your 644output buffer, and a total of output_height scanlines will be returned. 645 646Note: if you are using the JPEG library's internal memory manager to allocate 647data buffers (as djpeg does), then the manager's protocol requires that you 648request large buffers *before* calling jpeg_start_decompress(). This is a 649little tricky since the output_XXX fields are not normally valid then. You 650can make them valid by calling jpeg_calc_output_dimensions() after setting the 651relevant parameters (scaling, output color space, and quantization flag). 652 653 6546. while (scan lines remain to be read) 655 jpeg_read_scanlines(...); 656 657Now you can read the decompressed image data by calling jpeg_read_scanlines() 658one or more times. At each call, you pass in the maximum number of scanlines 659to be read (ie, the height of your working buffer); jpeg_read_scanlines() 660will return up to that many lines. The return value is the number of lines 661actually read. The format of the returned data is discussed under "Data 662formats", above. Don't forget that grayscale and color JPEGs will return 663different data formats! 664 665Image data is returned in top-to-bottom scanline order. If you must write 666out the image in bottom-to-top order, you can use the JPEG library's virtual 667array mechanism to invert the data efficiently. Examples of this can be 668found in the sample application djpeg. 669 670The library maintains a count of the number of scanlines returned so far 671in the output_scanline field of the JPEG object. Usually you can just use 672this variable as the loop counter, so that the loop test looks like 673"while (cinfo.output_scanline < cinfo.output_height)". (Note that the test 674should NOT be against image_height, unless you never use scaling. The 675image_height field is the height of the original unscaled image.) 676The return value always equals the change in the value of output_scanline. 677 678If you don't use a suspending data source, it is safe to assume that 679jpeg_read_scanlines() reads at least one scanline per call, until the 680bottom of the image has been reached. 681 682If you use a buffer larger than one scanline, it is NOT safe to assume that 683jpeg_read_scanlines() fills it. (The current implementation returns only a 684few scanlines per call, no matter how large a buffer you pass.) So you must 685always provide a loop that calls jpeg_read_scanlines() repeatedly until the 686whole image has been read. 687 688 6897. jpeg_finish_decompress(...); 690 691After all the image data has been read, call jpeg_finish_decompress() to 692complete the decompression cycle. This causes working memory associated 693with the JPEG object to be released. 694 695Typical code: 696 697 jpeg_finish_decompress(&cinfo); 698 699If using the stdio source manager, don't forget to close the source stdio 700stream if necessary. 701 702It is an error to call jpeg_finish_decompress() before reading the correct 703total number of scanlines. If you wish to abort decompression, call 704jpeg_abort() as discussed below. 705 706After completing a decompression cycle, you may dispose of the JPEG object as 707discussed next, or you may use it to decompress another image. In that case 708return to step 2 or 3 as appropriate. If you do not change the source 709manager, the next image will be read from the same source. 710 711 7128. Release the JPEG decompression object. 713 714When you are done with a JPEG decompression object, destroy it by calling 715jpeg_destroy_decompress() or jpeg_destroy(). The previous discussion of 716destroying compression objects applies here too. 717 718Typical code: 719 720 jpeg_destroy_decompress(&cinfo); 721 722 7239. Aborting. 724 725You can abort a decompression cycle by calling jpeg_destroy_decompress() or 726jpeg_destroy() if you don't need the JPEG object any more, or 727jpeg_abort_decompress() or jpeg_abort() if you want to reuse the object. 728The previous discussion of aborting compression cycles applies here too. 729 730 731Mechanics of usage: include files, linking, etc 732----------------------------------------------- 733 734Applications using the JPEG library should include the header file jpeglib.h 735to obtain declarations of data types and routines. Before including 736jpeglib.h, include system headers that define at least the typedefs FILE and 737size_t. On ANSI-conforming systems, including <stdio.h> is sufficient; on 738older Unix systems, you may need <sys/types.h> to define size_t. 739 740If the application needs to refer to individual JPEG library error codes, also 741include jerror.h to define those symbols. 742 743jpeglib.h indirectly includes the files jconfig.h and jmorecfg.h. If you are 744installing the JPEG header files in a system directory, you will want to 745install all four files: jpeglib.h, jerror.h, jconfig.h, jmorecfg.h. 746 747The most convenient way to include the JPEG code into your executable program 748is to prepare a library file ("libjpeg.a", or a corresponding name on non-Unix 749machines) and reference it at your link step. If you use only half of the 750library (only compression or only decompression), only that much code will be 751included from the library, unless your linker is hopelessly brain-damaged. 752The supplied makefiles build libjpeg.a automatically (see install.txt). 753 754While you can build the JPEG library as a shared library if the whim strikes 755you, we don't really recommend it. The trouble with shared libraries is that 756at some point you'll probably try to substitute a new version of the library 757without recompiling the calling applications. That generally doesn't work 758because the parameter struct declarations usually change with each new 759version. In other words, the library's API is *not* guaranteed binary 760compatible across versions; we only try to ensure source-code compatibility. 761(In hindsight, it might have been smarter to hide the parameter structs from 762applications and introduce a ton of access functions instead. Too late now, 763however.) 764 765On some systems your application may need to set up a signal handler to ensure 766that temporary files are deleted if the program is interrupted. This is most 767critical if you are on MS-DOS and use the jmemdos.c memory manager back end; 768it will try to grab extended memory for temp files, and that space will NOT be 769freed automatically. See cjpeg.c or djpeg.c for an example signal handler. 770 771It may be worth pointing out that the core JPEG library does not actually 772require the stdio library: only the default source/destination managers and 773error handler need it. You can use the library in a stdio-less environment 774if you replace those modules and use jmemnobs.c (or another memory manager of 775your own devising). More info about the minimum system library requirements 776may be found in jinclude.h. 777 778 779ADVANCED FEATURES 780================= 781 782Compression parameter selection 783------------------------------- 784 785This section describes all the optional parameters you can set for JPEG 786compression, as well as the "helper" routines provided to assist in this 787task. Proper setting of some parameters requires detailed understanding 788of the JPEG standard; if you don't know what a parameter is for, it's best 789not to mess with it! See REFERENCES in the README file for pointers to 790more info about JPEG. 791 792It's a good idea to call jpeg_set_defaults() first, even if you plan to set 793all the parameters; that way your code is more likely to work with future JPEG 794libraries that have additional parameters. For the same reason, we recommend 795you use a helper routine where one is provided, in preference to twiddling 796cinfo fields directly. 797 798The helper routines are: 799 800jpeg_set_defaults (j_compress_ptr cinfo) 801 This routine sets all JPEG parameters to reasonable defaults, using 802 only the input image's color space (field in_color_space, which must 803 already be set in cinfo). Many applications will only need to use 804 this routine and perhaps jpeg_set_quality(). 805 806jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace) 807 Sets the JPEG file's colorspace (field jpeg_color_space) as specified, 808 and sets other color-space-dependent parameters appropriately. See 809 "Special color spaces", below, before using this. A large number of 810 parameters, including all per-component parameters, are set by this 811 routine; if you want to twiddle individual parameters you should call 812 jpeg_set_colorspace() before rather than after. 813 814jpeg_default_colorspace (j_compress_ptr cinfo) 815 Selects an appropriate JPEG colorspace based on cinfo->in_color_space, 816 and calls jpeg_set_colorspace(). This is actually a subroutine of 817 jpeg_set_defaults(). It's broken out in case you want to change 818 just the colorspace-dependent JPEG parameters. 819 820jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline) 821 Constructs JPEG quantization tables appropriate for the indicated 822 quality setting. The quality value is expressed on the 0..100 scale 823 recommended by IJG (cjpeg's "-quality" switch uses this routine). 824 Note that the exact mapping from quality values to tables may change 825 in future IJG releases as more is learned about DCT quantization. 826 If the force_baseline parameter is TRUE, then the quantization table 827 entries are constrained to the range 1..255 for full JPEG baseline 828 compatibility. In the current implementation, this only makes a 829 difference for quality settings below 25, and it effectively prevents 830 very small/low quality files from being generated. The IJG decoder 831 is capable of reading the non-baseline files generated at low quality 832 settings when force_baseline is FALSE, but other decoders may not be. 833 834jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor, 835 boolean force_baseline) 836 Same as jpeg_set_quality() except that the generated tables are the 837 sample tables given in the JPEC spec section K.1, multiplied by the 838 specified scale factor (which is expressed as a percentage; thus 839 scale_factor = 100 reproduces the spec's tables). Note that larger 840 scale factors give lower quality. This entry point is useful for 841 conforming to the Adobe PostScript DCT conventions, but we do not 842 recommend linear scaling as a user-visible quality scale otherwise. 843 force_baseline again constrains the computed table entries to 1..255. 844 845int jpeg_quality_scaling (int quality) 846 Converts a value on the IJG-recommended quality scale to a linear 847 scaling percentage. Note that this routine may change or go away 848 in future releases --- IJG may choose to adopt a scaling method that 849 can't be expressed as a simple scalar multiplier, in which case the 850 premise of this routine collapses. Caveat user. 851 852jpeg_default_qtables (j_compress_ptr cinfo, boolean force_baseline) 853 Set default quantization tables with linear q_scale_factor[] values 854 (see below). 855 856jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl, 857 const unsigned int *basic_table, 858 int scale_factor, boolean force_baseline) 859 Allows an arbitrary quantization table to be created. which_tbl 860 indicates which table slot to fill. basic_table points to an array 861 of 64 unsigned ints given in normal array order. These values are 862 multiplied by scale_factor/100 and then clamped to the range 1..65535 863 (or to 1..255 if force_baseline is TRUE). 864 CAUTION: prior to library version 6a, jpeg_add_quant_table expected 865 the basic table to be given in JPEG zigzag order. If you need to 866 write code that works with either older or newer versions of this 867 routine, you must check the library version number. Something like 868 "#if JPEG_LIB_VERSION >= 61" is the right test. 869 870jpeg_simple_progression (j_compress_ptr cinfo) 871 Generates a default scan script for writing a progressive-JPEG file. 872 This is the recommended method of creating a progressive file, 873 unless you want to make a custom scan sequence. You must ensure that 874 the JPEG color space is set correctly before calling this routine. 875 876 877Compression parameters (cinfo fields) include: 878 879int block_size 880 Set DCT block size. All N from 1 to 16 are possible. 881 Default is 8 (baseline format). 882 Larger values produce higher compression, 883 smaller values produce higher quality. 884 An exact DCT stage is possible with 1 or 2. 885 With the default quality of 75 and default Luminance qtable 886 the DCT+Quantization stage is lossless for value 1. 887 Note that values other than 8 require a SmartScale capable decoder, 888 introduced with IJG JPEG 8. Setting the block_size parameter for 889 compression works with version 8c and later. 890 891J_DCT_METHOD dct_method 892 Selects the algorithm used for the DCT step. Choices are: 893 JDCT_ISLOW: slow but accurate integer algorithm 894 JDCT_IFAST: faster, less accurate integer method 895 JDCT_FLOAT: floating-point method 896 JDCT_DEFAULT: default method (normally JDCT_ISLOW) 897 JDCT_FASTEST: fastest method (normally JDCT_IFAST) 898 The FLOAT method is very slightly more accurate than the ISLOW method, 899 but may give different results on different machines due to varying 900 roundoff behavior. The integer methods should give the same results 901 on all machines. On machines with sufficiently fast FP hardware, the 902 floating-point method may also be the fastest. The IFAST method is 903 considerably less accurate than the other two; its use is not 904 recommended if high quality is a concern. JDCT_DEFAULT and 905 JDCT_FASTEST are macros configurable by each installation. 906 907unsigned int scale_num, scale_denom 908 Scale the image by the fraction scale_num/scale_denom. Default is 909 1/1, or no scaling. Currently, the supported scaling ratios are 910 M/N with all N from 1 to 16, where M is the destination DCT size, 911 which is 8 by default (see block_size parameter above). 912 (The library design allows for arbitrary scaling ratios but this 913 is not likely to be implemented any time soon.) 914 915J_COLOR_SPACE jpeg_color_space 916int num_components 917 The JPEG color space and corresponding number of components; see 918 "Special color spaces", below, for more info. We recommend using 919 jpeg_set_color_space() if you want to change these. 920 921boolean optimize_coding 922 TRUE causes the compressor to compute optimal Huffman coding tables 923 for the image. This requires an extra pass over the data and 924 therefore costs a good deal of space and time. The default is 925 FALSE, which tells the compressor to use the supplied or default 926 Huffman tables. In most cases optimal tables save only a few percent 927 of file size compared to the default tables. Note that when this is 928 TRUE, you need not supply Huffman tables at all, and any you do 929 supply will be overwritten. 930 931unsigned int restart_interval 932int restart_in_rows 933 To emit restart markers in the JPEG file, set one of these nonzero. 934 Set restart_interval to specify the exact interval in MCU blocks. 935 Set restart_in_rows to specify the interval in MCU rows. (If 936 restart_in_rows is not 0, then restart_interval is set after the 937 image width in MCUs is computed.) Defaults are zero (no restarts). 938 One restart marker per MCU row is often a good choice. 939 NOTE: the overhead of restart markers is higher in grayscale JPEG 940 files than in color files, and MUCH higher in progressive JPEGs. 941 If you use restarts, you may want to use larger intervals in those 942 cases. 943 944const jpeg_scan_info * scan_info 945int num_scans 946 By default, scan_info is NULL; this causes the compressor to write a 947 single-scan sequential JPEG file. If not NULL, scan_info points to 948 an array of scan definition records of length num_scans. The 949 compressor will then write a JPEG file having one scan for each scan 950 definition record. This is used to generate noninterleaved or 951 progressive JPEG files. The library checks that the scan array 952 defines a valid JPEG scan sequence. (jpeg_simple_progression creates 953 a suitable scan definition array for progressive JPEG.) This is 954 discussed further under "Progressive JPEG support". 955 956boolean do_fancy_downsampling 957 If TRUE, use direct DCT scaling with DCT size > 8 for downsampling 958 of chroma components. 959 If FALSE, use only DCT size <= 8 and simple separate downsampling. 960 Default is TRUE. 961 For better image stability in multiple generation compression cycles 962 it is preferable that this value matches the corresponding 963 do_fancy_upsampling value in decompression. 964 965int smoothing_factor 966 If non-zero, the input image is smoothed; the value should be 1 for 967 minimal smoothing to 100 for maximum smoothing. Consult jcsample.c 968 for details of the smoothing algorithm. The default is zero. 969 970boolean write_JFIF_header 971 If TRUE, a JFIF APP0 marker is emitted. jpeg_set_defaults() and 972 jpeg_set_colorspace() set this TRUE if a JFIF-legal JPEG color space 973 (ie, YCbCr or grayscale) is selected, otherwise FALSE. 974 975UINT8 JFIF_major_version 976UINT8 JFIF_minor_version 977 The version number to be written into the JFIF marker. 978 jpeg_set_defaults() initializes the version to 1.01 (major=minor=1). 979 You should set it to 1.02 (major=1, minor=2) if you plan to write 980 any JFIF 1.02 extension markers. 981 982UINT8 density_unit 983UINT16 X_density 984UINT16 Y_density 985 The resolution information to be written into the JFIF marker; 986 not used otherwise. density_unit may be 0 for unknown, 987 1 for dots/inch, or 2 for dots/cm. The default values are 0,1,1 988 indicating square pixels of unknown size. 989 990boolean write_Adobe_marker 991 If TRUE, an Adobe APP14 marker is emitted. jpeg_set_defaults() and 992 jpeg_set_colorspace() set this TRUE if JPEG color space RGB, CMYK, 993 or YCCK is selected, otherwise FALSE. It is generally a bad idea 994 to set both write_JFIF_header and write_Adobe_marker. In fact, 995 you probably shouldn't change the default settings at all --- the 996 default behavior ensures that the JPEG file's color space can be 997 recognized by the decoder. 998 999JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS] 1000 Pointers to coefficient quantization tables, one per table slot, 1001 or NULL if no table is defined for a slot. Usually these should 1002 be set via one of the above helper routines; jpeg_add_quant_table() 1003 is general enough to define any quantization table. The other 1004 routines will set up table slot 0 for luminance quality and table 1005 slot 1 for chrominance. 1006 1007int q_scale_factor[NUM_QUANT_TBLS] 1008 Linear quantization scaling factors (percentage, initialized 100) 1009 for use with jpeg_default_qtables(). 1010 See rdswitch.c and cjpeg.c for an example of usage. 1011 Note that the q_scale_factor[] fields are the "linear" scales, so you 1012 have to convert from user-defined ratings via jpeg_quality_scaling(). 1013 Here is an example code which corresponds to cjpeg -quality 90,70: 1014 1015 jpeg_set_defaults(cinfo); 1016 1017 /* Set luminance quality 90. */ 1018 cinfo->q_scale_factor[0] = jpeg_quality_scaling(90); 1019 /* Set chrominance quality 70. */ 1020 cinfo->q_scale_factor[1] = jpeg_quality_scaling(70); 1021 1022 jpeg_default_qtables(cinfo, force_baseline); 1023 1024 CAUTION: You must also set 1x1 subsampling for efficient separate 1025 color quality selection, since the default value used by library 1026 is 2x2: 1027 1028 cinfo->comp_info[0].v_samp_factor = 1; 1029 cinfo->comp_info[0].h_samp_factor = 1; 1030 1031JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS] 1032JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS] 1033 Pointers to Huffman coding tables, one per table slot, or NULL if 1034 no table is defined for a slot. Slots 0 and 1 are filled with the 1035 JPEG sample tables by jpeg_set_defaults(). If you need to allocate 1036 more table structures, jpeg_alloc_huff_table() may be used. 1037 Note that optimal Huffman tables can be computed for an image 1038 by setting optimize_coding, as discussed above; there's seldom 1039 any need to mess with providing your own Huffman tables. 1040 1041 1042The actual dimensions of the JPEG image that will be written to the file are 1043given by the following fields. These are computed from the input image 1044dimensions and the compression parameters by jpeg_start_compress(). You can 1045also call jpeg_calc_jpeg_dimensions() to obtain the values that will result 1046from the current parameter settings. This can be useful if you are trying 1047to pick a scaling ratio that will get close to a desired target size. 1048 1049JDIMENSION jpeg_width Actual dimensions of output image. 1050JDIMENSION jpeg_height 1051 1052 1053Per-component parameters are stored in the struct cinfo.comp_info[i] for 1054component number i. Note that components here refer to components of the 1055JPEG color space, *not* the source image color space. A suitably large 1056comp_info[] array is allocated by jpeg_set_defaults(); if you choose not 1057to use that routine, it's up to you to allocate the array. 1058 1059int component_id 1060 The one-byte identifier code to be recorded in the JPEG file for 1061 this component. For the standard color spaces, we recommend you 1062 leave the default values alone. 1063 1064int h_samp_factor 1065int v_samp_factor 1066 Horizontal and vertical sampling factors for the component; must 1067 be 1..4 according to the JPEG standard. Note that larger sampling 1068 factors indicate a higher-resolution component; many people find 1069 this behavior quite unintuitive. The default values are 2,2 for 1070 luminance components and 1,1 for chrominance components, except 1071 for grayscale where 1,1 is used. 1072 1073int quant_tbl_no 1074 Quantization table number for component. The default value is 1075 0 for luminance components and 1 for chrominance components. 1076 1077int dc_tbl_no 1078int ac_tbl_no 1079 DC and AC entropy coding table numbers. The default values are 1080 0 for luminance components and 1 for chrominance components. 1081 1082int component_index 1083 Must equal the component's index in comp_info[]. (Beginning in 1084 release v6, the compressor library will…
Large files files are truncated, but you can click here to view the full file