1 /*=========================================================================
4 Module: $RCSfile: gdcmJpeg.cxx,v $
6 Date: $Date: 2005/01/26 11:42:02 $
7 Version: $Revision: 1.37 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.html for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
18 #include "gdcmFileHelper.h"
19 #include "gdcmJPEGFragment.h"
22 DICOM provides a mechanism for supporting the use of JPEG Image Compression
23 through the Encapsulated Format (see PS 3.3 of the DICOM Standard).
24 Annex A defines a number of Transfer Syntaxes which reference
25 the JPEG Standard and provide a number of lossless (bit preserving)
26 and lossy compression schemes.
27 In order to facilitate interoperability of implementations conforming
28 to the DICOM Standard which elect to use one or more
29 of the Transfer Syntaxes for JPEG Image Compression, the following policy is specified:
31 Any implementation which conforms to the DICOM Standard and has elected
32 to support any one of the Transfer Syntaxes for lossless JPEG Image Compression,
33 shall support the following lossless compression:
34 The subset (first-order horizontal prediction [Selection Value 1) of JPEG Process 14
35 (DPCM, non-hierarchical with Huffman coding) (see Annex F of the DICOM Standard).
37 Any implementation which conforms to the DICOM Standard and has elected
38 to support any one of the Transfer Syntaxes for 8-bit lossy JPEG Image Compression,
39 shall support the JPEG Baseline Compression (coding Process 1).
41 Any implementation which conforms to the DICOM Standard and has elected
42 to support any one of the Transfer Syntaxes for 12-bit lossy JPEG Image Compression,
43 shall support the JPEG Compression Process 4.
45 Note: The DICOM conformance statement shall differentiate between implementations
46 that can simply receive JPEG encoded images and those that can receive and process
47 JPEG encoded images (see PS 3.2 of the DICOM Standard).
49 The use of the DICOM Encapsulated Format to support JPEG Compressed Pixel Data
50 implies that the Data Elements which are related to the Native Format Pixel Data encoding
51 (e.g. Bits Allocated, Bits Stored, High Bit, Pixel Representation, Rows, Columns, etc.)
52 shall contain values which are consistent with the characteristics
53 of the uncompressed pixel data from which the compressed Data Stream was derived.
54 The Pixel Data characteristics included in the JPEG Interchange Format
55 shall be used to decode the compressed data stream.
57 Run Length Encoding Compression
59 DICOM provides a mechanism for supporting the use of Run Length Encoding (RLE)
60 Compression which is a byte oriented lossless compression scheme through
61 the encapsulated Format (see PS 3.3 of this Standard).
62 Annex G of the DICOM Standard defines RLE Compression and its Transfer Syntax.
64 Note: The RLE Compression algorithm described in Annex G
65 of the DICOM Standard is the compression used in
66 the TIFF 6.0 specification known as the "PackBits" scheme.
68 The use of the DICOM Encapsulated Format to support RLE Compressed Pixel Data
69 implies that the Data Elements which are related to the Native Format Pixel Data encoding (
70 e.g. Bits Allocated, Bits Stored, High Bit, Pixel Representation, Rows, Columns, etc.)
71 shall contain values which are consistent with the characteristics
72 of the uncompressed pixel data from which the compressed data is derived
76 * <setjmp.h> is used for the optional error recovery mechanism shown in
77 * the second part of the example.
81 * Include file for users of JPEG library.
82 * You will need to have included system headers that define at least
83 * the typedefs FILE and size_t before you can include jpeglib.h.
84 * (stdio.h is sufficient on ANSI-conforming systems.)
85 * You may also wish to include "jerror.h".
87 #if defined(__sgi) && !defined(__GNUC__)
88 // Try to get rid of the warning:
89 //cc-3505 CC: WARNING File = /usr/include/internal/setjmp_core.h, Line = 74
90 // setjmp not marked as unknown_control_flow because it is not declared as a
93 // #pragma unknown_control_flow (setjmp)
94 # if (_COMPILER_VERSION >= 730)
95 # pragma set woff 3505
99 // Let us get rid of this funny warning on /W4:
100 // warning C4611: interaction between '_setjmp' and C++ object
101 // destruction is non-portable
102 #pragma warning( disable : 4611 )
107 #include "jdatasrc.cxx"
108 #include "jdatadst.cxx"
112 /******************** JPEG COMPRESSION SAMPLE INTERFACE *******************/
114 /* This half of the example shows how to feed data into the JPEG compressor.
115 * We present a minimal version that does not worry about refinements such
116 * as error recovery (the JPEG code will just exit() if it gets an error).
120 * IMAGE DATA FORMATS:
122 * The standard input image format is a rectangular array of pixels, with
123 * each pixel having the same number of "component" values (color channels).
124 * Each pixel row is an array of JSAMPLEs (which typically are unsigned chars).
125 * If you are working with color data, then the color values for each pixel
126 * must be adjacent in the row; for example, R,G,B,R,G,B,R,G,B,... for 24-bit
129 * For this example, we'll assume that this data structure matches the way
130 * our application has stored the image in memory, so we can just pass a
131 * pointer to our image buffer. In particular, let's say that the image is
132 * RGB color and is described by:
136 //extern JSAMPLE * image_buffer; /* Points to large array of R,G,B-order data */
137 //extern int image_height; /* Number of rows in image */
138 //extern int image_width; /* Number of columns in image */
143 * Sample routine for JPEG compression. We assume that the target file name
144 * and a compression quality factor are passed in.
148 * \brief routine for JPEG decompression
149 * @param fp pointer to an already open file descriptor
150 * 8 significant bits per pixel
151 * @param im_buf Points to array (of R,G,B-order) data to compress
152 * @param quality compression quality
153 * @param image_height Number of rows in image
154 * @param image_width Number of columns in image
155 * @return 1 on success, 0 on error
158 bool gdcm_write_JPEG_file (std::ofstream* fp, void* im_buf,
159 int image_width, int image_height, int quality)
162 JSAMPLE* image_buffer = (JSAMPLE*) im_buf;
164 /* This struct contains the JPEG compression parameters and pointers to
165 * working space (which is allocated as needed by the JPEG library).
166 * It is possible to have several such structures, representing multiple
167 * compression/decompression processes, in existence at once. We refer
168 * to any one struct (and its associated working data) as a "JPEG object".
170 struct jpeg_compress_struct cinfo;
171 /* This struct represents a JPEG error handler. It is declared separately
172 * because applications often want to supply a specialized error handler
173 * (see the second half of this file for an example). But here we just
174 * take the easy way out and use the standard error handler, which will
175 * print a message on stderr and call exit() if compression fails.
176 * Note that this struct must live as long as the main JPEG parameter
177 * struct, to avoid dangling-pointer problems.
179 struct jpeg_error_mgr jerr;
181 //FILE* outfile; /* target FILE* /
182 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
183 int row_stride; /* physical row width in image buffer */
185 /* Step 1: allocate and initialize JPEG compression object */
187 /* We have to set up the error handler first, in case the initialization
188 * step fails. (Unlikely, but it could happen if you are out of memory.)
189 * This routine fills in the contents of struct jerr, and returns jerr's
190 * address which we place into the link field in cinfo.
192 cinfo.err = jpeg_std_error(&jerr);
193 /* Now we can initialize the JPEG compression object. */
194 jpeg_create_compress(&cinfo);
196 /* Step 2: specify data destination (eg, a file) */
197 /* Note: steps 2 and 3 can be done in either order. */
199 /* Here we use the library-supplied code to send compressed data to a
200 * stdio stream. You can also write your own code to do something else.
201 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
202 * requires it in order to write binary files.
204 // if ((outfile = fopen(filename, "wb")) == NULL) {
205 // fprintf(stderr, "can't open %s\n", filename);
209 jpeg_stdio_dest(&cinfo, fp);
211 /* Step 3: set parameters for compression */
213 /* First we supply a description of the input image.
214 * Four fields of the cinfo struct must be filled in:
216 cinfo.image_width = image_width;/* image width and height, in pixels */
217 cinfo.image_height = image_height;
218 cinfo.input_components = 3; /* # of color components per pixel */
219 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
220 /* Now use the library's routine to set default compression parameters.
221 * (You must set at least cinfo.in_color_space before calling this,
222 * since the defaults depend on the source color space.)
224 jpeg_set_defaults(&cinfo);
225 /* Now you can set any non-default parameters you wish to.
226 * Here we just illustrate the use of quality (quantization table) scaling:
228 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
230 /* Step 4: Start compressor */
232 /* TRUE ensures that we will write a complete interchange-JPEG file.
233 * Pass TRUE unless you are very sure of what you're doing.
235 jpeg_start_compress(&cinfo, TRUE);
237 /* Step 5: while (scan lines remain to be written) */
238 /* jpeg_write_scanlines(...); */
240 /* Here we use the library's state variable cinfo.next_scanline as the
241 * loop counter, so that we don't have to keep track ourselves.
242 * To keep things simple, we pass one scanline per call; you can pass
243 * more if you wish, though.
245 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
247 while (cinfo.next_scanline < cinfo.image_height) {
248 /* jpeg_write_scanlines expects an array of pointers to scanlines.
249 * Here the array is only one element long, but you could pass
250 * more than one scanline at a time if that's more convenient.
252 row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
254 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
257 /* Step 6: Finish compression */
259 jpeg_finish_compress(&cinfo);
261 /* After finish_compress, we can close the output file. */
263 // fclose(fp); --> the caller will close (multiframe treatement)
265 /* Step 7: release JPEG compression object */
267 /* This is an important step since it will release a good deal of memory. */
268 jpeg_destroy_compress(&cinfo);
270 /* And we're done! */
280 * In the above loop, we ignored the return value of jpeg_write_scanlines,
281 * which is the number of scanlines actually written. We could get away
282 * with this because we were only relying on the value of cinfo.next_scanline,
283 * which will be incremented correctly. If you maintain additional loop
284 * variables then you should be careful to increment them properly.
285 * Actually, for output to a stdio stream you needn't worry, because
286 * then jpeg_write_scanlines will write all the lines passed (or else exit
287 * with a fatal error). Partial writes can only occur if you use a data
288 * destination module that can demand suspension of the compressor.
289 * (If you don't know what that's for, you don't need it.)
291 * If the compressor requires full-image buffers (for entropy-coding
292 * optimization or a multi-scan JPEG file), it will create temporary
293 * files for anything that doesn't fit within the maximum-memory setting.
294 * (Note that temp files are NOT needed if you use the default parameters.)
295 * On some systems you may need to set up a signal handler to ensure that
296 * temporary files are deleted if the program is interrupted. See libjpeg.doc.
298 * Scanlines MUST be supplied in top-to-bottom order if you want your JPEG
299 * files to be compatible with everyone else's. If you cannot readily read
300 * your data in that order, you'll need an intermediate array to hold the
301 * image. See rdtarga.c or rdbmp.c for examples of handling bottom-to-top
302 * source data using the JPEG code's internal virtual-array mechanisms.
307 /******************** JPEG DECOMPRESSION SAMPLE INTERFACE *******************/
309 /* This half of the example shows how to read data from the JPEG decompressor.
310 * It's a bit more refined than the above, in that we show:
311 * (a) how to modify the JPEG library's standard error-reporting behavior;
312 * (b) how to allocate workspace using the library's memory manager.
314 * Just to make this example a little different from the first one, we'll
315 * assume that we do not intend to put the whole image into an in-memory
316 * buffer, but to send it line-by-line someplace else. We need a one-
317 * scanline-high JSAMPLE array as a work buffer, and we will let the JPEG
318 * memory manager allocate it for us. This approach is actually quite useful
319 * because we don't need to remember to deallocate the buffer separately: it
320 * will go away automatically when the JPEG object is cleaned up.
326 * The JPEG library's standard error handler (jerror.c) is divided into
327 * several "methods" which you can override individually. This lets you
328 * adjust the behavior without duplicating a lot of code, which you might
329 * have to update with each future release.
331 * Our example here shows how to override the "error_exit" method so that
332 * control is returned to the library's caller when a fatal error occurs,
333 * rather than calling exit() as the standard error_exit method does.
335 * We use C's setjmp/longjmp facility to return control. This means that the
336 * routine which calls the JPEG library must first execute a setjmp() call to
337 * establish the return point. We want the replacement error_exit to do a
338 * longjmp(). But we need to make the setjmp buffer accessible to the
339 * error_exit routine. To do this, we make a private extension of the
340 * standard JPEG error handler object. (If we were using C++, we'd say we
341 * were making a subclass of the regular error handler.)
343 * Here's the extended error handler struct:
346 //-----------------------------------------------------------------------------
347 struct my_error_mgr {
348 struct jpeg_error_mgr pub; /* "public" fields */
349 jmp_buf setjmp_buffer; /* for return to caller */
351 typedef struct my_error_mgr* my_error_ptr;
352 //-----------------------------------------------------------------------------
355 * Here's the routine that will replace the standard error_exit method:
357 METHODDEF(void) my_error_exit (j_common_ptr cinfo) {
358 /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
359 my_error_ptr myerr = (my_error_ptr) cinfo->err;
361 /* Always display the message. */
362 /* We could postpone this until after returning, if we chose. */
363 (*cinfo->err->output_message) (cinfo);
365 /* Return control to the setjmp point */
366 longjmp(myerr->setjmp_buffer, 1);
369 //-----------------------------------------------------------------------------
371 * Sample routine for JPEG decompression. We assume that the source file name
372 * is passed in. We want to return 1 on success, 0 on error.
376 * \brief routine for JPEG decompression
377 * @param fp pointer to an already open file descriptor
378 * 8 significant bits per pixel
379 * @param image_buffer to receive uncompressed pixels
380 * @return 1 on success, 0 on error
383 bool JPEGFragment::gdcm_read_JPEG_file (std::ifstream* fp, void* image_buffer , int& statesuspension)
385 //static int fragimage = 0;
386 //std::cerr << "Image Fragment:" << fragimage++ << std::endl;
387 pImage = (uint8_t*)image_buffer;
388 /* This struct contains the JPEG decompression parameters and pointers to
389 * working space (which is allocated as needed by the JPEG library).
391 static struct jpeg_decompress_struct cinfo;
393 /* -------------- inside, we found :
394 * JDIMENSION image_width; // input image width
395 * JDIMENSION image_height; // input image height
396 * int input_components; // nb of color components in input image
397 * J_COLOR_SPACE in_color_space; // colorspace of input image
398 * double input_gamma; // image gamma of input image
401 /* We use our private extension JPEG error handler.
402 * Note that this struct must live as long as the main JPEG parameter
403 * struct, to avoid dangling-pointer problems.
405 struct my_error_mgr jerr;
408 JSAMPARRAY buffer;/* Output row buffer */
412 // typedef unsigned char JSAMPLE;
413 // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
414 // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
415 // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
417 int row_stride;/* physical row width in output buffer */
419 //std::cerr << "StateSuspension: " << statesuspension << std::endl;
420 //#define GDCM_JPG_DEBUG
421 #ifdef GDCM_JPG_DEBUG
422 printf("entree dans File::gdcm_read_JPEG_file (i.e. 8), depuis gdcmJpeg\n");
423 #endif //GDCM_JPG_DEBUG
425 /* In this example we want to open the input file before doing anything else,
426 * so that the setjmp() error recovery below can assume the file is open.
427 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
428 * requires it in order to read binary files.
431 /* Step 1: allocate and initialize JPEG decompression object */
432 #ifdef GDCM_JPG_DEBUG
433 printf("Entree Step 1\n");
434 #endif //GDCM_JPG_DEBUG
436 /* We set up the normal JPEG error routines, then override error_exit. */
438 cinfo.err = jpeg_std_error(&jerr.pub);
439 jerr.pub.error_exit = my_error_exit;
441 /* Establish the setjmp return context for my_error_exit to use. */
442 if (setjmp(jerr.setjmp_buffer))
444 /* If we get here, the JPEG code has signaled an error.
445 * We need to clean up the JPEG object, close the input file, and return.
447 std::cerr << "Qu'est c'est ce bordel !!!!!" << std::endl;
448 jpeg_destroy_decompress(&cinfo);
451 /* Now we can initialize the JPEG decompression object. */
452 if( statesuspension == 0 )
454 jpeg_create_decompress(&cinfo);
455 /* Step 2: specify data source (eg, a file) */
456 #ifdef GDCM_JPG_DEBUG
457 printf("Entree Step 2\n");
458 #endif //GDCM_JPG_DEBUG
460 jpeg_stdio_src(&cinfo, fp, this, 1);
465 jpeg_stdio_src(&cinfo, fp, this, 0);
467 /* Step 3: read file parameters with jpeg_read_header() */
468 #ifdef GDCM_JPG_DEBUG
469 printf("Entree Step 3\n");
470 #endif //GDCM_JPG_DEBUG
472 if( statesuspension < 2 )
474 if( jpeg_read_header(&cinfo, TRUE) == JPEG_SUSPENDED )
476 std::cerr << "Suspension: jpeg_read_header" << std::endl;
479 /* We can ignore the return value from jpeg_read_header since
480 * (a) suspension is not possible with the stdio data source, and
481 * (b) we passed TRUE to reject a tables-only JPEG file as an error.
482 * See libjpeg.doc for more info.
485 // prevent the library from performing any color space conversion
486 if( cinfo.process == JPROC_LOSSLESS )
488 cinfo.jpeg_color_space = JCS_UNKNOWN;
489 cinfo.out_color_space = JCS_UNKNOWN;
492 } //statesuspension < 2
494 #ifdef GDCM_JPG_DEBUG
495 printf("--------------Header contents :----------------\n");
496 printf("image_width %d image_height %d\n",
497 cinfo.image_width , cinfo.image_height);
498 printf("bits of precision in image data %d \n",
499 cinfo.output_components);
500 printf("nb of color components returned %d \n",
501 cinfo.data_precision);
502 #endif //GDCM_JPG_DEBUG
506 * JDIMENSION image_width; // input image width
507 * JDIMENSION image_height; // input image height
508 * int output_components; // # of color components returned
509 * J_COLOR_SPACE in_color_space; // colorspace of input image
510 * double input_gamma; // image gamma of input image
511 * int data_precision; // bits of precision in image data
514 /* Step 4: set parameters for decompression */
515 #ifdef GDCM_JPG_DEBUG
516 printf("Entree Step 4\n");
517 #endif //GDCM_JPG_DEBUG
518 /* In this example, we don't need to change any of the defaults set by
519 * jpeg_read_header(), so we do nothing here.
522 /* Step 5: Start decompressor */
523 #ifdef GDCM_JPG_DEBUG
524 printf("Entree Step 5\n");
525 #endif //GDCM_JPG_DEBUG
527 if(statesuspension < 3 )
529 if( jpeg_start_decompress(&cinfo) == FALSE )
531 std::cerr << "Suspension: jpeg_start_decompress" << std::endl;
533 /* We can ignore the return value since suspension is not possible
534 * with the stdio data source.
537 /* We may need to do some setup of our own at this point before reading
538 * the data. After jpeg_start_decompress() we have the correct scaled
539 * output image dimensions available, as well as the output colormap
540 * if we asked for color quantization.
541 * In this example, we need to make an output work buffer of the right size.
544 /* JSAMPLEs per row in output buffer */
545 row_stride = cinfo.output_width * cinfo.output_components*2;
547 #ifdef GDCM_JPG_DEBUG
548 printf ("cinfo.output_width %d cinfo.output_components %d row_stride %d\n",
549 cinfo.output_width, cinfo.output_components,row_stride);
550 #endif //GDCM_JPG_DEBUG
552 /* Make a one-row-high sample array that will go away when done with image */
553 buffer = (*cinfo.mem->alloc_sarray)
554 ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
556 /* Step 6: while (scan lines remain to be read) */
557 #ifdef GDCM_JPG_DEBUG
558 printf("Entree Step 6\n");
559 #endif //GDCM_JPG_DEBUG
560 /* jpeg_read_scanlines(...); */
562 /* Here we use the library's state variable cinfo.output_scanline as the
563 * loop counter, so that we don't have to keep track ourselves.
565 #ifdef GDCM_JPG_DEBUG
566 printf ("cinfo.output_height %d cinfo.output_width %d\n",
567 cinfo.output_height,cinfo.output_width);
568 #endif //GDCM_JPG_DEBUG
571 } // statesuspension < 3
574 buffer = (JSAMPARRAY)SampBuffer;
576 int bufsize = cinfo.output_width * cinfo.output_components;
577 size_t rowsize = bufsize * sizeof(JSAMPLE);
579 while (cinfo.output_scanline < cinfo.output_height) {
580 /* jpeg_read_scanlines expects an array of pointers to scanlines.
581 * Here the array is only one element long, but you could ask for
582 * more than one scanline at a time if that's more convenient.
585 //printf( "scanlines: %d\n",cinfo.output_scanline);
586 if( jpeg_read_scanlines(&cinfo, buffer, 1) == 0 )
588 std::cerr << "Suspension: jpeg_read_scanlines" << std::endl;
592 // The ijg has no notion of big endian, therefore always swap the jpeg stream
593 #if defined(GDCM_WORDS_BIGENDIAN) && (CMAKE_BITS_IN_JSAMPLE != 8)
594 uint16_t *buffer16 = (uint16_t*)*buffer;
595 uint16_t *pimage16 = (uint16_t*)pImage;
596 for(unsigned int i=0;i<rowsize/2;i++)
597 pimage16[i] = (buffer16[i] >> 8) | (buffer16[i] << 8 );
599 memcpy( pImage, *buffer,rowsize);
600 #endif //GDCM_WORDS_BIGENDIAN
604 /* Step 7: Finish decompression */
605 #ifdef GDCM_JPG_DEBUG
606 printf("Entree Step 7\n");
607 #endif //GDCM_JPG_DEBUG
609 if( jpeg_finish_decompress(&cinfo) == FALSE )
611 std::cerr << "Suspension: jpeg_finish_decompress" << std::endl;
614 /* We can ignore the return value since suspension is not possible
615 * with the stdio data source.
618 /* Step 8: Release JPEG decompression object */
620 #ifdef GDCM_JPG_DEBUG
621 printf("Entree Step 8\n");
622 #endif //GDCM_JPG_DEBUG
624 /* This is an important step since it will release a good deal of memory. */
626 jpeg_destroy_decompress(&cinfo);
627 //std::cerr << "jpeg_destroy_decompress" << std::endl;
629 /* After finish_decompress, we can close the input file.
630 * Here we postpone it until after no more JPEG errors are possible,
631 * so as to simplify the setjmp error logic above. (Actually, I don't
632 * think that jpeg_destroy can do an error exit, but why assume anything...)
635 /* At this point you may want to check to see whether any corrupt-data
636 * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
639 /* And we're done! */
648 * In the above code, we ignored the return value of jpeg_read_scanlines,
649 * which is the number of scanlines actually read. We could get away with
650 * this because we asked for only one line at a time and we weren't using
651 * a suspending data source. See libjpeg.doc for more info.
653 * We cheated a bit by calling alloc_sarray() after jpeg_start_decompress();
654 * we should have done it beforehand to ensure that the space would be
655 * counted against the JPEG max_memory setting. In some systems the above
656 * code would risk an out-of-memory error. However, in general we don't
657 * know the output image dimensions before jpeg_start_decompress(), unless we
658 * call jpeg_calc_output_dimensions(). See libjpeg.doc for more about this.
660 * Scanlines are returned in the same order as they appear in the JPEG file,
661 * which is standardly top-to-bottom. If you must emit data bottom-to-top,
662 * you can use one of the virtual arrays provided by the JPEG memory manager
663 * to invert the data. See wrbmp.c for an example.
665 * As with compression, some operating modes may require temporary files.
666 * On some systems you may need to set up a signal handler to ensure that
667 * temporary files are deleted if the program is interrupted. See libjpeg.doc.
670 // Put the warning back
671 #pragma warning( default : 4611 )
674 //----------------------------------------------------------------------------
678 * \brief routine for JPEG decompression from a memory buffer.
679 * routine for JPEG decompression from a memory buffer. This routine
680 * only reads one JPEG image at a time, but returns information about
681 * how many bytes have been consumed from the \c input_buffer, and
682 * how many bytes have been written into the output \c image_buffer.
684 * @param input_buffer pointer to a memory buffer containing the jpeg
686 * @param buflen length of the memory buffer.
687 * @param image_buffer pointer to the location where the decompressed
688 * image will be filled.
689 * @param howManyRead returns how many bytes have been consumed from the
691 * @param howManyWritten returns how many bytes have been written into
692 * the output image_buffer.
693 * @return 1 on success, 0 on error
696 bool gdcm_read_JPEG_memory ( const JOCTET* input_buffer, const size_t buflen,
698 size_t *howManyRead, size_t *howManyWritten)
700 volatile char * pimage=(volatile char *)image_buffer;
701 JOCTET* input = (JOCTET*) input_buffer;
703 /* This struct contains the JPEG decompression parameters and pointers to
704 * working space (which is allocated as needed by the JPEG library).
706 struct jpeg_decompress_struct cinfo;
708 /* -------------- inside, we found :
709 * JDIMENSION image_width; // input image width
710 * JDIMENSION image_height; // input image height
711 * int input_components; // nb of color components in input image
712 * J_COLOR_SPACE in_color_space; // colorspace of input image
713 * double input_gamma; // image gamma of input image
716 /* We use our private extension JPEG error handler.
717 * Note that this struct must live as long as the main JPEG parameter
718 * struct, to avoid dangling-pointer problems.
720 struct my_error_mgr jerr;
723 JSAMPARRAY buffer;/* Output row buffer */
727 // typedef unsigned char JSAMPLE;
728 // typedef JSAMPLE FAR *JSAMPROW;/* ptr to one image row of pixel samples. */
729 // typedef JSAMPROW *JSAMPARRAY;/* ptr to some rows (a 2-D sample array) */
730 // typedef JSAMPARRAY *JSAMPIMAGE;/* a 3-D sample array: top index is color */
732 int row_stride;/* physical row width in output buffer */
734 #ifdef GDCM_JPG_DEBUG
735 printf("entree dans File::gdcm_read_JPEG_file (i.e. 8), depuis gdcmJpeg\n");
736 #endif //GDCM_JPG_DEBUG
738 /* In this example we want to open the input file before doing anything else,
739 * so that the setjmp() error recovery below can assume the file is open.
740 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
741 * requires it in order to read binary files.
744 /* Step 1: allocate and initialize JPEG decompression object */
745 #ifdef GDCM_JPG_DEBUG
746 printf("Entree Step 1\n");
747 #endif //GDCM_JPG_DEBUG
749 /* We set up the normal JPEG error routines, then override error_exit. */
751 cinfo.err = jpeg_std_error(&jerr.pub);
752 jerr.pub.error_exit = my_error_exit;
754 /* Establish the setjmp return context for my_error_exit to use. */
755 if (setjmp(jerr.setjmp_buffer))
757 /* If we get here, the JPEG code has signaled an error.
758 * We need to clean up the JPEG object, close the input file, and return.
760 jpeg_destroy_decompress(&cinfo);
762 *howManyRead += input - input_buffer;
763 *howManyWritten += pimage - (char *)image_buffer;
767 /* Now we can initialize the JPEG decompression object. */
768 jpeg_create_decompress(&cinfo);
770 /* Step 2: specify data source (eg, a file) */
771 #ifdef GDCM_JPG_DEBUG
772 printf("Entree Step 2\n");
773 #endif //GDCM_JPG_DEBUG
775 jpeg_memory_src(&cinfo, input, buflen);
777 /* Step 3: read file parameters with jpeg_read_header() */
778 #ifdef GDCM_JPG_DEBUG
779 printf("Entree Step 3\n");
780 #endif //GDCM_JPG_DEBUG
782 (void) jpeg_read_header(&cinfo, TRUE);
784 /* We can ignore the return value from jpeg_read_header since
785 * (a) suspension is not possible with the stdio data source, and
786 * (b) we passed TRUE to reject a tables-only JPEG file as an error.
787 * See libjpeg.doc for more info.
790 // prevent the library from performing any color space conversion
791 if( cinfo.process == JPROC_LOSSLESS )
793 cinfo.jpeg_color_space = JCS_UNKNOWN;
794 cinfo.out_color_space = JCS_UNKNOWN;
797 #ifdef GDCM_JPG_DEBUG
798 printf("--------------Header contents :----------------\n");
799 printf("image_width %d image_height %d\n",
800 cinfo.image_width , cinfo.image_height);
801 printf("bits of precision in image data %d \n",
802 cinfo.output_components);
803 printf("nb of color components returned %d \n",
804 cinfo.data_precision);
805 #endif //GDCM_JPG_DEBUG
809 * JDIMENSION image_width; // input image width
810 * JDIMENSION image_height; // input image height
811 * int output_components; // # of color components returned
812 * J_COLOR_SPACE in_color_space; // colorspace of input image
813 * double input_gamma; // image gamma of input image
814 * int data_precision; // bits of precision in image data
817 /* Step 4: set parameters for decompression */
818 #ifdef GDCM_JPG_DEBUG
819 printf("Entree Step 4\n");
820 #endif //GDCM_JPG_DEBUG
821 /* In this example, we don't need to change any of the defaults set by
822 * jpeg_read_header(), so we do nothing here.
825 /* Step 5: Start decompressor */
826 #ifdef GDCM_JPG_DEBUG
827 printf("Entree Step 5\n");
828 #endif //GDCM_JPG_DEBUG
830 (void) jpeg_start_decompress(&cinfo);
831 /* We can ignore the return value since suspension is not possible
832 * with the stdio data source.
835 /* We may need to do some setup of our own at this point before reading
836 * the data. After jpeg_start_decompress() we have the correct scaled
837 * output image dimensions available, as well as the output colormap
838 * if we asked for color quantization.
839 * In this example, we need to make an output work buffer of the right size.
842 /* JSAMPLEs per row in output buffer */
843 row_stride = cinfo.output_width * cinfo.output_components*2;
845 #ifdef GDCM_JPG_DEBUG
846 printf ("cinfo.output_width %d cinfo.output_components %d row_stride %d\n",
847 cinfo.output_width, cinfo.output_components,row_stride);
848 #endif //GDCM_JPG_DEBUG
850 /* Make a one-row-high sample array that will go away when done with image */
851 buffer = (*cinfo.mem->alloc_sarray)
852 ((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);
855 /* Step 6: while (scan lines remain to be read) */
856 #ifdef GDCM_JPG_DEBUG
857 printf("Entree Step 6\n");
858 #endif //GDCM_JPG_DEBUG
859 /* jpeg_read_scanlines(...); */
861 /* Here we use the library's state variable cinfo.output_scanline as the
862 * loop counter, so that we don't have to keep track ourselves.
864 #ifdef GDCM_JPG_DEBUG
865 printf ("cinfo.output_height %d cinfo.output_width %d\n",
866 cinfo.output_height,cinfo.output_width);
867 #endif //GDCM_JPG_DEBUG
869 int bufsize = cinfo.output_width * cinfo.output_components;
870 size_t rowsize = bufsize * sizeof(JSAMPLE);
872 while (cinfo.output_scanline < cinfo.output_height) {
873 /* jpeg_read_scanlines expects an array of pointers to scanlines.
874 * Here the array is only one element long, but you could ask for
875 * more than one scanline at a time if that's more convenient.
878 //printf( "scanlines: %d\n",cinfo.output_scanline);
879 (void) jpeg_read_scanlines(&cinfo, buffer, 1);
880 #if defined(GDCM_WORDS_BIGENDIAN) && (CMAKE_BITS_IN_JSAMPLE != 8)
881 uint16_t *buffer16 = (uint16_t*)*buffer;
882 uint16_t *pimage16 = (uint16_t*)pimage;
883 for(unsigned int i=0;i<rowsize/2;i++)
884 pimage16[i] = (buffer16[i] >> 8) | (buffer16[i] << 8 );
886 memcpy( (void*)pimage, *buffer,rowsize);
887 #endif //GDCM_WORDS_BIGENDIAN
891 /* Step 7: Finish decompression */
892 #ifdef GDCM_JPG_DEBUG
893 printf("Entree Step 7\n");
894 #endif //GDCM_JPG_DEBUG
896 input = (JOCTET *)cinfo.src->next_input_byte;
898 (void) jpeg_finish_decompress(&cinfo);
900 /* We can ignore the return value since suspension is not possible
901 * with the stdio data source.
904 /* Step 8: Release JPEG decompression object */
906 #ifdef GDCM_JPG_DEBUG
907 printf("Entree Step 8\n");
908 #endif //GDCM_JPG_DEBUG
910 /* This is an important step since it will release a good deal of memory. */
912 jpeg_destroy_decompress(&cinfo);
915 /* After finish_decompress, we can close the input file.
916 * Here we postpone it until after no more JPEG errors are possible,
917 * so as to simplify the setjmp error logic above. (Actually, I don't
918 * think that jpeg_destroy can do an error exit, but why assume anything...)
921 /* At this point you may want to check to see whether any corrupt-data
922 * warnings occurred (test whether jerr.pub.num_warnings is nonzero).
925 /* And we're done! */
926 *howManyRead += input - input_buffer;
927 *howManyWritten += pimage - (char *)image_buffer;
932 } // end namespace gdcm