libjpeg.doc
上传用户:zlh9724
上传日期:2007-01-04
资源大小:1991k
文件大小:141k
源码类别:

浏览器

开发平台:

Unix_Linux

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