example.c 17 KB

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