Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/external/source/vncdll/winvnc/libjpeg/example.c
Views: 11784
/*1* example.c2*3* This file illustrates how to use the IJG code as a subroutine library4* to read or write JPEG image files. You should look at this code in5* conjunction with the documentation file libjpeg.doc.6*7* This code will not do anything useful as-is, but it may be helpful as a8* skeleton for constructing routines that call the JPEG library.9*10* We present these routines in the same coding style used in the JPEG code11* (ANSI function definitions, etc); but you are of course free to code your12* routines in a different style if you prefer.13*/1415#include <stdio.h>1617/*18* Include file for users of JPEG library.19* You will need to have included system headers that define at least20* the typedefs FILE and size_t before you can include jpeglib.h.21* (stdio.h is sufficient on ANSI-conforming systems.)22* You may also wish to include "jerror.h".23*/2425#include "jpeglib.h"2627/*28* <setjmp.h> is used for the optional error recovery mechanism shown in29* the second part of the example.30*/3132#include <setjmp.h>33343536/******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/3738/* This half of the example shows how to feed data into the JPEG compressor.39* We present a minimal version that does not worry about refinements such40* as error recovery (the JPEG code will just exit() if it gets an error).41*/424344/*45* IMAGE DATA FORMATS:46*47* The standard input image format is a rectangular array of pixels, with48* each pixel having the same number of "component" values (color channels).49* Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).50* If you are working with color data, then the color values for each pixel51* must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit52* RGB color.53*54* For this example, we'll assume that this data structure matches the way55* our application has stored the image in memory, so we can just pass a56* pointer to our image buffer. In particular, let's say that the image is57* RGB color and is described by:58*/5960extern JSAMPLE * image_buffer; /* Points to large array of R,G,B-order data */61extern int image_height; /* Number of rows in image */62extern int image_width; /* Number of columns in image */636465/*66* Sample routine for JPEG compression. We assume that the target file name67* and a compression quality factor are passed in.68*/6970GLOBAL(void)71write_JPEG_file (char * filename, int quality)72{73/* This struct contains the JPEG compression parameters and pointers to74* working space (which is allocated as needed by the JPEG library).75* It is possible to have several such structures, representing multiple76* compression/decompression processes, in existence at once. We refer77* to any one struct (and its associated working data) as a "JPEG object".78*/79struct jpeg_compress_struct cinfo;80/* This struct represents a JPEG error handler. It is declared separately81* because applications often want to supply a specialized error handler82* (see the second half of this file for an example). But here we just83* take the easy way out and use the standard error handler, which will84* print a message on stderr and call exit() if compression fails.85* Note that this struct must live as long as the main JPEG parameter86* struct, to avoid dangling-pointer problems.87*/88struct jpeg_error_mgr jerr;89/* More stuff */90FILE * outfile; /* target file */91JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */92int row_stride; /* physical row width in image buffer */9394/* Step 1: allocate and initialize JPEG compression object */9596/* We have to set up the error handler first, in case the initialization97* step fails. (Unlikely, but it could happen if you are out of memory.)98* This routine fills in the contents of struct jerr, and returns jerr's99* address which we place into the link field in cinfo.100*/101cinfo.err = jpeg_std_error(&jerr);102/* Now we can initialize the JPEG compression object. */103jpeg_create_compress(&cinfo);104105/* Step 2: specify data destination (eg, a file) */106/* Note: steps 2 and 3 can be done in either order. */107108/* Here we use the library-supplied code to send compressed data to a109* stdio stream. You can also write your own code to do something else.110* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that111* requires it in order to write binary files.112*/113if ((outfile = fopen(filename, "wb")) == NULL) {114fprintf(stderr, "can't open %s\n", filename);115exit(1);116}117jpeg_stdio_dest(&cinfo, outfile);118119/* Step 3: set parameters for compression */120121/* First we supply a description of the input image.122* Four fields of the cinfo struct must be filled in:123*/124cinfo.image_width = image_width; /* image width and height, in pixels */125cinfo.image_height = image_height;126cinfo.input_components = 3; /* # of color components per pixel */127cinfo.in_color_space = JCS_RGB; /* colorspace of input image */128/* Now use the library's routine to set default compression parameters.129* (You must set at least cinfo.in_color_space before calling this,130* since the defaults depend on the source color space.)131*/132jpeg_set_defaults(&cinfo);133/* Now you can set any non-default parameters you wish to.134* Here we just illustrate the use of quality (quantization table) scaling:135*/136jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);137138/* Step 4: Start compressor */139140/* TRUE ensures that we will write a complete interchange-JPEG file.141* Pass TRUE unless you are very sure of what you're doing.142*/143jpeg_start_compress(&cinfo, TRUE);144145/* Step 5: while (scan lines remain to be written) */146/* jpeg_write_scanlines(...); */147148/* Here we use the library's state variable cinfo.next_scanline as the149* loop counter, so that we don't have to keep track ourselves.150* To keep things simple, we pass one scanline per call; you can pass151* more if you wish, though.152*/153row_stride = image_width * 3; /* JSAMPLEs per row in image_buffer */154155while (cinfo.next_scanline < cinfo.image_height) {156/* jpeg_write_scanlines expects an array of pointers to scanlines.157* Here the array is only one element long, but you could pass158* more than one scanline at a time if that's more convenient.159*/160row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];161(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);162}163164/* Step 6: Finish compression */165166jpeg_finish_compress(&cinfo);167/* After finish_compress, we can close the output file. */168fclose(outfile);169170/* Step 7: release JPEG compression object */171172/* This is an important step since it will release a good deal of memory. */173jpeg_destroy_compress(&cinfo);174175/* And we're done! */176}177178179/*180* SOME FINE POINTS:181*182* In the above loop, we ignored the return value of jpeg_write_scanlines,183* which is the number of scanlines actually written. We could get away184* with this because we were only relying on the value of cinfo.next_scanline,185* which will be incremented correctly. If you maintain additional loop186* variables then you should be careful to increment them properly.187* Actually, for output to a stdio stream you needn't worry, because188* then jpeg_write_scanlines will write all the lines passed (or else exit189* with a fatal error). Partial writes can only occur if you use a data190* destination module that can demand suspension of the compressor.191* (If you don't know what that's for, you don't need it.)192*193* If the compressor requires full-image buffers (for entropy-coding194* optimization or a multi-scan JPEG file), it will create temporary195* files for anything that doesn't fit within the maximum-memory setting.196* (Note that temp files are NOT needed if you use the default parameters.)197* On some systems you may need to set up a signal handler to ensure that198* temporary files are deleted if the program is interrupted. See libjpeg.doc.199*200* Scanlines MUST be supplied in top-to-bottom order if you want your JPEG201* files to be compatible with everyone else's. If you cannot readily read202* your data in that order, you'll need an intermediate array to hold the203* image. See rdtarga.c or rdbmp.c for examples of handling bottom-to-top204* source data using the JPEG code's internal virtual-array mechanisms.205*/206207208209/******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/210211/* This half of the example shows how to read data from the JPEG decompressor.212* It's a bit more refined than the above, in that we show:213* (a) how to modify the JPEG library's standard error-reporting behavior;214* (b) how to allocate workspace using the library's memory manager.215*216* Just to make this example a little different from the first one, we'll217* assume that we do not intend to put the whole image into an in-memory218* buffer, but to send it line-by-line someplace else. We need a one-219* scanline-high JSAMPLE array as a work buffer, and we will let the JPEG220* memory manager allocate it for us. This approach is actually quite useful221* because we don't need to remember to deallocate the buffer separately: it222* will go away automatically when the JPEG object is cleaned up.223*/224225226/*227* ERROR HANDLING:228*229* The JPEG library's standard error handler (jerror.c) is divided into230* several "methods" which you can override individually. This lets you231* adjust the behavior without duplicating a lot of code, which you might232* have to update with each future release.233*234* Our example here shows how to override the "error_exit" method so that235* control is returned to the library's caller when a fatal error occurs,236* rather than calling exit() as the standard error_exit method does.237*238* We use C's setjmp/longjmp facility to return control. This means that the239* routine which calls the JPEG library must first execute a setjmp() call to240* establish the return point. We want the replacement error_exit to do a241* longjmp(). But we need to make the setjmp buffer accessible to the242* error_exit routine. To do this, we make a private extension of the243* standard JPEG error handler object. (If we were using C++, we'd say we244* were making a subclass of the regular error handler.)245*246* Here's the extended error handler struct:247*/248249struct my_error_mgr {250struct jpeg_error_mgr pub; /* "public" fields */251252jmp_buf setjmp_buffer; /* for return to caller */253};254255typedef struct my_error_mgr * my_error_ptr;256257/*258* Here's the routine that will replace the standard error_exit method:259*/260261METHODDEF(void)262my_error_exit (j_common_ptr cinfo)263{264/* cinfo->err really points to a my_error_mgr struct, so coerce pointer */265my_error_ptr myerr = (my_error_ptr) cinfo->err;266267/* Always display the message. */268/* We could postpone this until after returning, if we chose. */269(*cinfo->err->output_message) (cinfo);270271/* Return control to the setjmp point */272longjmp(myerr->setjmp_buffer, 1);273}274275276/*277* Sample routine for JPEG decompression. We assume that the source file name278* is passed in. We want to return 1 on success, 0 on error.279*/280281282GLOBAL(int)283read_JPEG_file (char * filename)284{285/* This struct contains the JPEG decompression parameters and pointers to286* working space (which is allocated as needed by the JPEG library).287*/288struct jpeg_decompress_struct cinfo;289/* We use our private extension JPEG error handler.290* Note that this struct must live as long as the main JPEG parameter291* struct, to avoid dangling-pointer problems.292*/293struct my_error_mgr jerr;294/* More stuff */295FILE * infile; /* source file */296JSAMPARRAY buffer; /* Output row buffer */297int row_stride; /* physical row width in output buffer */298299/* In this example we want to open the input file before doing anything else,300* so that the setjmp() error recovery below can assume the file is open.301* VERY IMPORTANT: use "b" option to fopen() if you are on a machine that302* requires it in order to read binary files.303*/304305if ((infile = fopen(filename, "rb")) == NULL) {306fprintf(stderr, "can't open %s\n", filename);307return 0;308}309310/* Step 1: allocate and initialize JPEG decompression object */311312/* We set up the normal JPEG error routines, then override error_exit. */313cinfo.err = jpeg_std_error(&jerr.pub);314jerr.pub.error_exit = my_error_exit;315/* Establish the setjmp return context for my_error_exit to use. */316if (setjmp(jerr.setjmp_buffer)) {317/* If we get here, the JPEG code has signaled an error.318* We need to clean up the JPEG object, close the input file, and return.319*/320jpeg_destroy_decompress(&cinfo);321fclose(infile);322return 0;323}324/* Now we can initialize the JPEG decompression object. */325jpeg_create_decompress(&cinfo);326327/* Step 2: specify data source (eg, a file) */328329jpeg_stdio_src(&cinfo, infile);330331/* Step 3: read file parameters with jpeg_read_header() */332333(void) jpeg_read_header(&cinfo, TRUE);334/* We can ignore the return value from jpeg_read_header since335* (a) suspension is not possible with the stdio data source, and336* (b) we passed TRUE to reject a tables-only JPEG file as an error.337* See libjpeg.doc for more info.338*/339340/* Step 4: set parameters for decompression */341342/* In this example, we don't need to change any of the defaults set by343* jpeg_read_header(), so we do nothing here.344*/345346/* Step 5: Start decompressor */347348(void) jpeg_start_decompress(&cinfo);349/* We can ignore the return value since suspension is not possible350* with the stdio data source.351*/352353/* We may need to do some setup of our own at this point before reading354* the data. After jpeg_start_decompress() we have the correct scaled355* output image dimensions available, as well as the output colormap356* if we asked for color quantization.357* In this example, we need to make an output work buffer of the right size.358*/359/* JSAMPLEs per row in output buffer */360row_stride = cinfo.output_width * cinfo.output_components;361/* Make a one-row-high sample array that will go away when done with image */362buffer = (*cinfo.mem->alloc_sarray)363((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);364365/* Step 6: while (scan lines remain to be read) */366/* jpeg_read_scanlines(...); */367368/* Here we use the library's state variable cinfo.output_scanline as the369* loop counter, so that we don't have to keep track ourselves.370*/371while (cinfo.output_scanline < cinfo.output_height) {372/* jpeg_read_scanlines expects an array of pointers to scanlines.373* Here the array is only one element long, but you could ask for374* more than one scanline at a time if that's more convenient.375*/376(void) jpeg_read_scanlines(&cinfo, buffer, 1);377/* Assume put_scanline_someplace wants a pointer and sample count. */378put_scanline_someplace(buffer[0], row_stride);379}380381/* Step 7: Finish decompression */382383(void) jpeg_finish_decompress(&cinfo);384/* We can ignore the return value since suspension is not possible385* with the stdio data source.386*/387388/* Step 8: Release JPEG decompression object */389390/* This is an important step since it will release a good deal of memory. */391jpeg_destroy_decompress(&cinfo);392393/* After finish_decompress, we can close the input file.394* Here we postpone it until after no more JPEG errors are possible,395* so as to simplify the setjmp error logic above. (Actually, I don't396* think that jpeg_destroy can do an error exit, but why assume anything...)397*/398fclose(infile);399400/* At this point you may want to check to see whether any corrupt-data401* warnings occurred (test whether jerr.pub.num_warnings is nonzero).402*/403404/* And we're done! */405return 1;406}407408409/*410* SOME FINE POINTS:411*412* In the above code, we ignored the return value of jpeg_read_scanlines,413* which is the number of scanlines actually read. We could get away with414* this because we asked for only one line at a time and we weren't using415* a suspending data source. See libjpeg.doc for more info.416*417* We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();418* we should have done it beforehand to ensure that the space would be419* counted against the JPEG max_memory setting. In some systems the above420* code would risk an out-of-memory error. However, in general we don't421* know the output image dimensions before jpeg_start_decompress(), unless we422* call jpeg_calc_output_dimensions(). See libjpeg.doc for more about this.423*424* Scanlines are returned in the same order as they appear in the JPEG file,425* which is standardly top-to-bottom. If you must emit data bottom-to-top,426* you can use one of the virtual arrays provided by the JPEG memory manager427* to invert the data. See wrbmp.c for an example.428*429* As with compression, some operating modes may require temporary files.430* On some systems you may need to set up a signal handler to ensure that431* temporary files are deleted if the program is interrupted. See libjpeg.doc.432*/433434435