example.txt 18 KB

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