1 /*=========================================================================
4 Module: $RCSfile: WriteDicomAsJPEG.cxx,v $
6 Date: $Date: 2006/08/18 16:08:16 $
7 Version: $Revision: 1.13 $
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 =========================================================================*/
20 #include "gdcmFileHelper.h"
28 #include "gdcmjpeg/8/jconfig.h"
29 #include "gdcmjpeg/8/jpeglib.h"
30 #include "gdcmjpeg/8/jinclude.h"
31 #include "gdcmjpeg/8/jerror.h"
34 #if defined(__BORLANDC__)
35 #include <mem.h> // for memcpy
38 #include "gdcmJPEGFragment.h"
42 #include "jdatasrc.cxx"
43 #include "jdatadst.cxx"
45 typedef std::pair<size_t, uint32_t> JpegPair; //offset, jpeg size
46 typedef std::vector<JpegPair> JpegVector;
48 void WriteDICOMItems(std::ostream *fp, JpegVector &v)
51 uint16_t group = 0xfffe;
52 uint16_t elem = 0xe000;
53 gdcm::binary_write(*fp, group);
54 gdcm::binary_write(*fp, elem);
56 uint32_t dummy = 0x12345678;
57 size_t offset = fp->tellp();
61 gdcm::binary_write(*fp, dummy);
65 void EncodeWithoutBasicOffsetTable(std::ostream *fp, int numFrag)// JpegVector& v) //, uint32_t length)
67 assert( numFrag == 1);
70 uint16_t group = 0xfffe;
71 uint16_t elem = 0xe000;
72 gdcm::binary_write(*fp, group);
73 gdcm::binary_write(*fp, elem);
75 uint32_t item_length = 0x0000;
76 gdcm::binary_write(*fp, item_length);
81 void EncodeWithBasicOffsetTable(std::ostream *fp, int numFrag, size_t &start)
84 uint16_t group = 0xfffe;
85 uint16_t elem = 0xe000;
86 gdcm::binary_write(*fp, group);
87 gdcm::binary_write(*fp, elem);
89 uint32_t item_length = numFrag*4; // sizeof(uint32_t)
90 gdcm::binary_write(*fp, item_length);
92 // Just prepare the space
93 start = fp->tellp(); //to be able to rewind
94 for(int i=0; i<numFrag;++i)
96 uint32_t dummy = 0x0000;
97 gdcm::binary_write(*fp, dummy);
101 void UpdateBasicOffsetTable(std::ostream *fp, JpegVector const &v, size_t pos)
103 JpegVector::const_iterator i;
105 const JpegPair &first = v[0];
106 for(i=v.begin(); i!=v.end(); ++i)
108 const JpegPair &jp = *i;
109 if(i == v.begin() ){ assert( jp.first - first.first == 0); }
110 uint32_t offset = jp.first - first.first;
111 gdcm::binary_write(*fp, offset);
112 //std::cerr << "Updating Table:" << jp.first - first.first << std::endl;
116 void UpdateJpegFragmentSize(std::ostream *fp, JpegVector const &v)
118 JpegVector::const_iterator i;
119 for(i= v.begin(); i!=v.end(); ++i)
121 const JpegPair &jp = *i;
122 fp->seekp( jp.first );
123 uint32_t length = jp.second;
124 gdcm::binary_write(*fp, length );
125 //std::cerr << "Updating:" << jp.first << "," << jp.second << std::endl;
129 void CloseJpeg(std::ostream *fp, JpegVector &v)
131 // sequence terminator
132 uint16_t group = 0xfffe;
133 uint16_t elem = 0xe000;
134 gdcm::binary_write(*fp, group);
135 gdcm::binary_write(*fp, elem);
137 uint32_t length = 0x0;
138 gdcm::binary_write(*fp, length);
140 // Jpeg is done, now update the frag length
141 UpdateJpegFragmentSize(fp, v);
144 bool InitializeJpeg(std::ostream *fp, int fragment_size, int image_width, int image_height,
145 int sample_pixel, int quality, struct jpeg_compress_struct &cinfo, int &row_stride)
148 /* This struct contains the JPEG compression parameters and pointers to
149 * working space (which is allocated as needed by the JPEG library).
150 * It is possible to have several such structures, representing multiple
151 * compression/decompression processes, in existence at once. We refer
152 * to any one struct (and its associated working data) as a "JPEG object".
154 //struct jpeg_compress_struct cinfo;
155 /* This struct represents a JPEG error handler. It is declared separately
156 * because applications often want to supply a specialized error handler
157 * (see the second half of this file for an example). But here we just
158 * take the easy way out and use the standard error handler, which will
159 * print a message on stderr and call exit() if compression fails.
160 * Note that this struct must live as long as the main JPEG parameter
161 * struct, to avoid dangling-pointer problems.
163 struct jpeg_error_mgr jerr;
166 /* Step 1: allocate and initialize JPEG compression object */
168 /* We have to set up the error handler first, in case the initialization
169 * step fails. (Unlikely, but it could happen if you are out of memory.)
170 * This routine fills in the contents of struct jerr, and returns jerr's
171 * address which we place into the link field in cinfo.
173 cinfo.err = jpeg_std_error(&jerr);
174 /* Now we can initialize the JPEG compression object. */
175 jpeg_create_compress(&cinfo);
177 /* Step 2: specify data destination (eg, a file) */
178 /* Note: steps 2 and 3 can be done in either order. */
180 jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
182 /* Step 3: set parameters for compression */
184 /* First we supply a description of the input image.
185 * Four fields of the cinfo struct must be filled in:
187 cinfo.image_width = image_width;/* image width and height, in pixels */
188 cinfo.image_height = image_height;
189 if ( sample_pixel == 3 )
191 cinfo.input_components = 3; /* # of color components per pixel */
192 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
196 cinfo.input_components = 1; /* # of color components per pixel */
197 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
199 /* Now use the library's routine to set default compression parameters.
200 * (You must set at least cinfo.in_color_space before calling this,
201 * since the defaults depend on the source color space.)
203 jpeg_set_defaults(&cinfo);
205 * http://www.koders.com/c/fid80DBBF1D49D004EF71CE7C493C34610C4F17D3D3.aspx
206 * http://studio.imagemagick.org/pipermail/magick-users/2002-September/004685.html
207 * You need to set -quality 101 or greater. If quality is 100 or less you
208 * get regular JPEG output. This is not explained in the documentation, only
209 * in the comments in coder/jpeg.c. When you have configured libjpeg with
210 * lossless support, then
212 * quality=predictor*100 + point_transform
214 * If you don't know what these values should be, just use 101.
215 * They only affect the compression ratio, not the image appearance,
218 jpeg_simple_lossless (&cinfo, 1, 1);
219 /* Now you can set any non-default parameters you wish to.
220 * Here we just illustrate the use of quality (quantization table) scaling:
222 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
224 /* Step 4: Start compressor */
226 /* TRUE ensures that we will write a complete interchange-JPEG file.
227 * Pass TRUE unless you are very sure of what you're doing.
229 jpeg_start_compress(&cinfo, TRUE);
231 /* Step 5: while (scan lines remain to be written) */
232 /* jpeg_write_scanlines(...); */
234 /* Here we use the library's state variable cinfo.next_scanline as the
235 * loop counter, so that we don't have to keep track ourselves.
236 * To keep things simple, we pass one scanline per call; you can pass
237 * more if you wish, though.
239 if (sample_pixel == 3)
241 assert( sample_pixel == 1 );
242 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
246 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
249 /* everything was ok */
253 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
255 /* Step 6: Finish compression */
257 jpeg_finish_compress(&cinfo);
259 /* Step 7: release JPEG compression object */
261 /* This is an important step since it will release a good deal of memory. */
262 jpeg_destroy_compress(&cinfo);
264 /* And we're done! */
268 // If false then suspension return
269 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
271 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
272 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
273 row_pointer[0] = image_buffer;
275 while (cinfo.next_scanline < cinfo.image_height) {
276 /* jpeg_write_scanlines expects an array of pointers to scanlines.
277 * Here the array is only one element long, but you could pass
278 * more than one scanline at a time if that's more convenient.
280 //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
282 if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
284 //entering suspension mode, basically we wrote the whole jpeg fragment
285 // technically we could enforce that by checkig the value of row_pointer to
286 // actually be at the end of the image...TODO
289 row_pointer[0] += row_stride;
292 // Well looks like we are done writting the scanlines
296 // input_buffer is ONE image
297 // fragment_size is the size of this image (fragment)
298 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
299 int image_width, int image_height, int numZ, int sample_pixel, int quality, JpegVector &v)
301 struct jpeg_compress_struct cinfo;
302 int row_stride; /* physical row width in image buffer */
303 size_t beg = fp->tellp();
304 bool r = InitializeJpeg(fp, fragment_size, image_width, image_height,
305 sample_pixel, quality, cinfo, row_stride);
309 uint8_t *pbuffer = (uint8_t*)input_buffer;
311 //for(i=0; i<numZ; ++i)
313 r = WriteScanlines(cinfo, pbuffer, row_stride);
315 // pbuffer+=fragment_size; //shift to next image
318 // size_t end = fp->tellp();
319 // std::cerr << "DIFF: " << end-beg << std::endl;
321 // JpegPair &jp = v[i];
322 // jp.second = end-beg;
326 r = FinalizeJpeg(cinfo);
328 size_t end = fp->tellp();
333 if( ((end-beg) % 2) )
338 assert( !(jp.second % 2) );
339 std::cerr << "DIFF: " << i <<" -> " << jp.second << std::endl;
343 //JpegPair &jp = v[0];
349 //bool CreateMultipleFrames (std::ostream *fp, void *input_buffer, int fragment_size,
350 // int image_width, int image_height, int sample_pixel, int quality, JpegVector &v)
354 #define WITHOFFSETTABLE 1
356 // Open a dicom file and compress it as JPEG stream
357 int main(int argc, char *argv[])
362 std::string filename = argv[1];
363 std::string outfilename = "/tmp/bla.dcm";
365 outfilename = argv[2];
368 quality = atoi(argv[2]);
369 std::cerr << "Using quality: " << quality << std::endl;
371 // Step 1 : Create the header of the image
372 gdcm::File *f = gdcm::File::New();
373 f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
374 f->SetFileName( filename );
377 gdcm::FileHelper *tested = gdcm::FileHelper::New( f );
378 std::string PixelType = tested->GetFile()->GetPixelType();
379 int xsize = f->GetXSize();
380 int ysize = f->GetYSize();
381 int zsize = f->GetZSize();
383 int samplesPerPixel = f->GetSamplesPerPixel();
384 size_t testedDataSize = tested->GetImageDataSize();
385 std::cerr << "testedDataSize:" << testedDataSize << std::endl;
386 uint8_t *testedImageData = tested->GetImageData();
388 //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
389 std::ostringstream *of = new std::ostringstream();
390 std::cout << "X: " << xsize << std::endl;
391 std::cout << "Y: " << ysize << std::endl;
392 std::cout << "Sample: " << samplesPerPixel << std::endl;
393 int fragment_size = xsize*ysize*samplesPerPixel;
395 JpegVector JpegFragmentSize;
397 size_t bots; //basic offset table start
398 EncodeWithBasicOffsetTable(of, zsize, bots);
400 EncodeWithoutBasicOffsetTable(of, 1);
402 uint8_t *pImageData = testedImageData;
403 for(int i=0; i<zsize;i++)
405 WriteDICOMItems(of, JpegFragmentSize);
406 CreateOneFrame(of, pImageData, fragment_size, xsize, ysize, zsize,
407 samplesPerPixel, quality, JpegFragmentSize);
408 assert( !(fragment_size % 2) );
409 pImageData += fragment_size;
411 CloseJpeg(of, JpegFragmentSize);
413 UpdateBasicOffsetTable(of, JpegFragmentSize, bots);
416 if( !f->IsReadable() )
418 std::cerr << "-------------------------------\n"
419 << "Error while creating the file\n"
420 << "This file is considered to be not readable\n";
424 std::streambuf* sb = of->rdbuf();
427 // Let save the file as jpeg standalone
429 std::ofstream *jof = new std::ofstream( "/tmp/test.jpg" );
430 CreateOneFrame(jof, testedImageData, fragment_size, xsize, ysize, zsize,
431 samplesPerPixel, 70, JpegFragmentSize);
440 // Step 1 : Create the header of the image
442 gdcm::File *fileToBuild = gdcm::File::New();
443 std::ostringstream str;
445 // Set the image size
448 fileToBuild->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
451 fileToBuild->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
457 fileToBuild->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
460 // Set the pixel type
462 str << 8; //img.componentSize;
463 fileToBuild->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
466 str << 8; //img.componentUse;
467 fileToBuild->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
470 str << 7; //( img.componentSize - 1 );
471 fileToBuild->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
473 // Set the pixel representation
475 str << 0; //img.sign;
476 fileToBuild->InsertEntryString(str.str(),0x0028,0x0103,"US"); // Pixel Representation
478 // Set the samples per pixel
480 str << samplesPerPixel; //img.components;
481 fileToBuild->InsertEntryString(str.str(),0x0028,0x0002,"US"); // Samples per Pixel
483 // Step 2 : Create the output image
484 // std::cout << "2...";
485 // if( img.componentSize%8 > 0 )
487 // img.componentSize += 8-img.componentSize%8;
489 size_t size = xsize * ysize * zsize
490 * samplesPerPixel /* * img.componentSize / 8*/;
492 uint8_t *imageData = new uint8_t[size];
493 gdcm::FileHelper *fileH = gdcm::FileHelper::New(fileToBuild);
494 //fileH->SetImageData(imageData,size);
495 assert( size == testedDataSize );
496 size = of->str().size();
497 //size = sb->in_avail();
498 std::cerr << "Size JPEG:" << size << std::endl;
499 //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
500 memcpy(imageData, of->str().c_str(), size);
501 fileH->SetImageData(imageData, size);
502 //str::string *s = of->str();
503 //fileH->SetWriteTypeToDcmExplVR();
504 fileH->SetWriteTypeToJPEG( );
505 if( !fileH->Write(outfilename) )
507 std::cerr << "Badddd" << std::endl;
510 std::ofstream out("/tmp/jpeg2.jpg");
511 //out.write( of->str(), of
512 //out << of->str(); //rdbuf is faster than going through str()
513 //out.write( (char*)imageData, size);
514 out.write( of->str().c_str(), size);
515 //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] <<
516 // imageData[8] << imageData[9] << std::endl;
523 fileToBuild->Delete();