]> Creatis software - gdcm.git/blob - Example/WriteDicomAsJPEG.cxx
Use gdcm1.3 features, to save CPU time
[gdcm.git] / Example / WriteDicomAsJPEG.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: WriteDicomAsJPEG.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/07/26 17:47:39 $
7   Version:   $Revision: 1.12 $
8                                                                                 
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.
12                                                                                 
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.
16                                                                                 
17 =========================================================================*/
18
19 #include "gdcmFile.h"
20 #include "gdcmFileHelper.h"
21 #include "gdcmUtil.h"
22  
23 #include <iostream>
24 #include <sstream>
25
26 #include <stdio.h>
27 extern "C" {
28 #include "gdcmjpeg/8/jconfig.h"
29 #include "gdcmjpeg/8/jpeglib.h"
30 #include "gdcmjpeg/8/jinclude.h"
31 #include "gdcmjpeg/8/jerror.h"
32 }
33
34 #if defined(__BORLANDC__)
35  #include <mem.h> // for memcpy
36 #endif
37
38 #include "gdcmJPEGFragment.h"
39 #include <setjmp.h>
40 #include <fstream>
41
42 #include "jdatasrc.cxx"
43 #include "jdatadst.cxx"
44
45 typedef std::pair<size_t, uint32_t> JpegPair; //offset, jpeg size
46 typedef std::vector<JpegPair> JpegVector;
47
48 void WriteDICOMItems(std::ostream *fp, JpegVector &v)
49 {
50   // Item tag:
51   uint16_t group = 0xfffe;
52   uint16_t elem  = 0xe000;
53   gdcm::binary_write(*fp, group);
54   gdcm::binary_write(*fp, elem);
55   // Item Length
56   uint32_t dummy = 0x12345678;
57   size_t offset = fp->tellp();
58   JpegPair jp;
59   jp.first = offset;
60   v.push_back(jp);
61   gdcm::binary_write(*fp, dummy);
62 }
63
64 // PS 3.5, page 66
65 void EncodeWithoutBasicOffsetTable(std::ostream *fp, int numFrag)// JpegVector& v) //, uint32_t length)
66 {
67   assert( numFrag == 1);
68
69   // Item tag:
70   uint16_t group = 0xfffe;
71   uint16_t elem  = 0xe000;
72   gdcm::binary_write(*fp, group);
73   gdcm::binary_write(*fp, elem);
74   // Item Length
75   uint32_t item_length = 0x0000;
76   gdcm::binary_write(*fp, item_length);
77
78 }
79
80 // PS 3.5, page 67
81 void EncodeWithBasicOffsetTable(std::ostream *fp, int numFrag, size_t &start)
82 {
83   // Item tag:
84   uint16_t group = 0xfffe;
85   uint16_t elem  = 0xe000;
86   gdcm::binary_write(*fp, group);
87   gdcm::binary_write(*fp, elem);
88   // Item Length
89   uint32_t item_length = numFrag*4; // sizeof(uint32_t)
90   gdcm::binary_write(*fp, item_length);
91
92   // Just prepare the space
93   start = fp->tellp(); //to be able to rewind
94   for(int i=0; i<numFrag;++i)
95     {
96     uint32_t dummy = 0x0000;
97     gdcm::binary_write(*fp, dummy);
98     }
99 }
100
101 void UpdateBasicOffsetTable(std::ostream *fp, JpegVector const &v, size_t pos)
102 {
103   JpegVector::const_iterator i;
104   fp->seekp( pos );
105   const JpegPair &first = v[0];
106   for(i=v.begin(); i!=v.end(); ++i)
107     {
108     const JpegPair &jp = *i;
109     if(i == v.begin() ){ assert( jp.first - first.first == 0); }
110     gdcm::binary_write(*fp, jp.first - first.first);
111     std::cerr << "Updating Table:" << jp.first - first.first << std::endl;
112     }
113 }
114
115 void UpdateJpegFragmentSize(std::ostream *fp, JpegVector const &v)
116 {
117   JpegVector::const_iterator i;
118   for(i= v.begin(); i!=v.end(); ++i)
119     {
120     const JpegPair &jp = *i;
121     fp->seekp( jp.first );
122     gdcm::binary_write(*fp, jp.second );
123     std::cerr << "Updating:" << jp.first << "," << jp.second << std::endl;
124     }
125 }
126
127 void CloseJpeg(std::ostream *fp, JpegVector &v)
128 {
129   // sequence terminator
130   uint16_t group = 0xfffe;
131   uint16_t elem  = 0xe000;
132   gdcm::binary_write(*fp, group);
133   gdcm::binary_write(*fp, elem);
134
135   uint32_t length = 0x0;
136   gdcm::binary_write(*fp, length);
137
138   // Jpeg is done, now update the frag length
139   UpdateJpegFragmentSize(fp, v);
140 }
141
142 bool InitializeJpeg(std::ostream *fp, int fragment_size, int image_width, int image_height, 
143   int sample_pixel, int quality, struct jpeg_compress_struct &cinfo, int &row_stride)
144 {
145
146   /* This struct contains the JPEG compression parameters and pointers to
147    * working space (which is allocated as needed by the JPEG library).
148    * It is possible to have several such structures, representing multiple
149    * compression/decompression processes, in existence at once.  We refer
150    * to any one struct (and its associated working data) as a "JPEG object".
151    */
152   //struct jpeg_compress_struct cinfo;
153   /* This struct represents a JPEG error handler.  It is declared separately
154    * because applications often want to supply a specialized error handler
155    * (see the second half of this file for an example).  But here we just
156    * take the easy way out and use the standard error handler, which will
157    * print a message on stderr and call exit() if compression fails.
158    * Note that this struct must live as long as the main JPEG parameter
159    * struct, to avoid dangling-pointer problems.
160    */
161   struct jpeg_error_mgr jerr;
162   /* More stuff */
163
164   /* Step 1: allocate and initialize JPEG compression object */
165
166   /* We have to set up the error handler first, in case the initialization
167    * step fails.  (Unlikely, but it could happen if you are out of memory.)
168    * This routine fills in the contents of struct jerr, and returns jerr's
169    * address which we place into the link field in cinfo.
170    */
171   cinfo.err = jpeg_std_error(&jerr);
172   /* Now we can initialize the JPEG compression object. */
173   jpeg_create_compress(&cinfo);
174
175   /* Step 2: specify data destination (eg, a file) */
176   /* Note: steps 2 and 3 can be done in either order. */
177
178   jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
179
180   /* Step 3: set parameters for compression */
181
182   /* First we supply a description of the input image.
183    * Four fields of the cinfo struct must be filled in:
184    */
185   cinfo.image_width = image_width;/* image width and height, in pixels */
186   cinfo.image_height = image_height;
187   if ( sample_pixel == 3 )
188     {
189     cinfo.input_components = 3;     /* # of color components per pixel */
190     cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
191     }
192   else
193     {
194     cinfo.input_components = 1;     /* # of color components per pixel */
195     cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
196     }
197   /* Now use the library's routine to set default compression parameters.
198    * (You must set at least cinfo.in_color_space before calling this,
199    * since the defaults depend on the source color space.)
200    */
201   jpeg_set_defaults(&cinfo);
202   /*
203    * http://www.koders.com/c/fid80DBBF1D49D004EF71CE7C493C34610C4F17D3D3.aspx
204    * http://studio.imagemagick.org/pipermail/magick-users/2002-September/004685.html
205    * You need to set -quality 101 or greater.  If quality is 100 or less you
206    * get regular JPEG output.  This is not explained in the documentation, only
207    * in the comments in coder/jpeg.c.  When you have configured libjpeg with
208    * lossless support, then
209    * 
210    *    quality=predictor*100 + point_transform
211    * 
212    * If you don't know what these values should be, just use 101.
213    * They only affect the compression ratio, not the image appearance,
214    * which is lossless.
215    */
216   jpeg_simple_lossless (&cinfo, 1, 1);
217   /* Now you can set any non-default parameters you wish to.
218    * Here we just illustrate the use of quality (quantization table) scaling:
219    */
220   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
221
222   /* Step 4: Start compressor */
223
224   /* TRUE ensures that we will write a complete interchange-JPEG file.
225    * Pass TRUE unless you are very sure of what you're doing.
226    */
227   jpeg_start_compress(&cinfo, TRUE);
228
229   /* Step 5: while (scan lines remain to be written) */
230   /*           jpeg_write_scanlines(...); */
231
232   /* Here we use the library's state variable cinfo.next_scanline as the
233    * loop counter, so that we don't have to keep track ourselves.
234    * To keep things simple, we pass one scanline per call; you can pass
235    * more if you wish, though.
236    */
237   if (sample_pixel == 3)
238     {
239     assert( sample_pixel == 1 );
240     row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
241     }
242   else
243     {
244     row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
245     }
246
247   /* everything was ok */
248   return true;
249 }
250
251 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
252 {
253   /* Step 6: Finish compression */
254
255   jpeg_finish_compress(&cinfo);
256   
257   /* Step 7: release JPEG compression object */
258
259   /* This is an important step since it will release a good deal of memory. */
260   jpeg_destroy_compress(&cinfo);
261
262   /* And we're done! */
263   return true;
264 }
265
266 // If false then suspension return
267 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
268 {
269   JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
270   JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
271   row_pointer[0] = image_buffer;
272
273   while (cinfo.next_scanline < cinfo.image_height) {
274     /* jpeg_write_scanlines expects an array of pointers to scanlines.
275      * Here the array is only one element long, but you could pass
276      * more than one scanline at a time if that's more convenient.
277      */
278     //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
279
280     if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
281       {
282       //entering suspension mode, basically we wrote the whole jpeg fragment
283       // technically we could enforce that by checkig the value of row_pointer to
284       // actually be at the end of the image...TODO
285       return false;
286       }
287     row_pointer[0] += row_stride;
288   }
289
290   // Well looks like we are done writting the scanlines
291   return true;
292 }
293
294 // input_buffer is ONE image
295 // fragment_size is the size of this image (fragment)
296 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
297                      int image_width, int image_height, int numZ, int sample_pixel, int quality, JpegVector &v)
298 {
299   struct jpeg_compress_struct cinfo;
300   int row_stride;            /* physical row width in image buffer */
301   size_t beg = fp->tellp();
302   bool r = InitializeJpeg(fp, fragment_size, image_width, image_height, 
303       sample_pixel, quality, cinfo, row_stride);
304   assert( r );
305   (void)numZ;
306
307   uint8_t *pbuffer = (uint8_t*)input_buffer;
308   //int i;
309   //for(i=0; i<numZ; ++i)
310 //    {
311     r = WriteScanlines(cinfo, pbuffer, row_stride);
312     assert( r );
313 //    pbuffer+=fragment_size; //shift to next image
314
315     //Upodate frag size
316 //    size_t end = fp->tellp();
317 //    std::cerr << "DIFF: " << end-beg << std::endl;
318
319 //    JpegPair &jp = v[i];
320 //    jp.second = end-beg;
321     //beg = end; //
322  //   }
323
324   r = FinalizeJpeg(cinfo);
325   assert( r );
326     size_t end = fp->tellp();
327     static int i = 0;
328     JpegPair &jp = v[i];
329     jp.second = end-beg;
330     
331     if( ((end-beg) % 2) )
332     {
333        fp->put( '\0' );
334        jp.second += 1;
335     }
336     assert( !(jp.second % 2) );
337     std::cerr << "DIFF: " << i <<" -> " << jp.second << std::endl;    
338        
339     ++i;
340
341   //JpegPair &jp = v[0];
342   //jp.second = 15328;
343
344   return true;
345 }
346
347 //bool CreateMultipleFrames (std::ostream *fp, void *input_buffer, int fragment_size,
348 //               int image_width, int image_height, int sample_pixel, int quality, JpegVector &v)
349 //{
350 //}
351
352 #define WITHOFFSETTABLE 1
353
354 // Open a dicom file and compress it as JPEG stream
355 int main(int argc, char *argv[])
356 {
357   if( argc < 2)
358     return 1;
359
360    std::string filename = argv[1];
361    std::string outfilename = "/tmp/bla.dcm";
362    if( argc >= 3 )
363      outfilename = argv[2];
364    int quality = 100;
365    if( argc >= 4 )
366      quality = atoi(argv[2]);
367    std::cerr << "Using quality: " << quality << std::endl;
368
369 // Step 1 : Create the header of the image
370    gdcm::File *f = gdcm::File::New();
371    f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
372    f->SetFileName( filename );
373    f->Load();
374
375    gdcm::FileHelper *tested = gdcm::FileHelper::New( f );
376    std::string PixelType = tested->GetFile()->GetPixelType();
377    int xsize = f->GetXSize();
378    int ysize = f->GetYSize();
379    int zsize = f->GetZSize();
380
381    int samplesPerPixel = f->GetSamplesPerPixel();
382    size_t testedDataSize    = tested->GetImageDataSize();
383    std::cerr << "testedDataSize:" << testedDataSize << std::endl;
384    uint8_t *testedImageData = tested->GetImageData();
385
386    //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
387    std::ostringstream *of = new std::ostringstream();
388    std::cout << "X: " << xsize << std::endl;
389    std::cout << "Y: " << ysize << std::endl;
390    std::cout << "Sample: " << samplesPerPixel << std::endl;
391    int fragment_size = xsize*ysize*samplesPerPixel;
392
393    JpegVector JpegFragmentSize;
394 #if WITHOFFSETTABLE
395    size_t bots; //basic offset table start
396    EncodeWithBasicOffsetTable(of, zsize, bots);
397 #else
398    EncodeWithoutBasicOffsetTable(of, 1);
399 #endif
400    uint8_t *pImageData = testedImageData;
401    for(int i=0; i<zsize;i++)
402      {
403      WriteDICOMItems(of, JpegFragmentSize);
404      CreateOneFrame(of, pImageData, fragment_size, xsize, ysize, zsize, 
405        samplesPerPixel, quality, JpegFragmentSize);
406      assert( !(fragment_size % 2) );  
407      pImageData += fragment_size;
408      }
409    CloseJpeg(of, JpegFragmentSize);
410 #if WITHOFFSETTABLE
411    UpdateBasicOffsetTable(of, JpegFragmentSize, bots);
412 #endif
413
414    if( !f->IsReadable() )
415    {
416       std::cerr << "-------------------------------\n"
417                 << "Error while creating the file\n"
418                 << "This file is considered to be not readable\n";
419
420       return 1;
421    }
422    std::streambuf* sb = of->rdbuf();
423    (void)sb;
424
425    // Let save the file as jpeg standalone
426      {
427      std::ofstream *jof = new std::ofstream( "/tmp/test.jpg" );
428      CreateOneFrame(jof, testedImageData, fragment_size, xsize, ysize, zsize, 
429        samplesPerPixel, 70, JpegFragmentSize);
430      jof->close();
431      delete jof;
432      }
433
434
435
436
437
438 // Step 1 : Create the header of the image
439
440    gdcm::File *fileToBuild = gdcm::File::New();
441    std::ostringstream str;
442
443    // Set the image size
444    str.str("");
445    str << xsize;
446    fileToBuild->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
447    str.str("");
448    str << ysize;
449    fileToBuild->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
450
451    if(zsize>1)
452    {
453       str.str("");
454       str << zsize;
455       fileToBuild->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
456    }
457
458    // Set the pixel type
459    str.str("");
460    str << 8; //img.componentSize;
461    fileToBuild->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
462
463    str.str("");
464    str << 8; //img.componentUse;
465    fileToBuild->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
466
467    str.str("");
468    str << 7; //( img.componentSize - 1 );
469    fileToBuild->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
470
471    // Set the pixel representation
472    str.str("");
473    str << 0; //img.sign;
474    fileToBuild->InsertEntryString(str.str(),0x0028,0x0103,"US"); // Pixel Representation
475
476    // Set the samples per pixel
477    str.str("");
478    str << samplesPerPixel; //img.components;
479    fileToBuild->InsertEntryString(str.str(),0x0028,0x0002,"US"); // Samples per Pixel
480
481 // Step 2 : Create the output image
482 //   std::cout << "2...";
483 //   if( img.componentSize%8 > 0 )
484 //   {
485 //      img.componentSize += 8-img.componentSize%8;
486 //   }
487    size_t size = xsize * ysize * zsize
488                * samplesPerPixel /* * img.componentSize / 8*/;
489
490    uint8_t *imageData = new uint8_t[size];
491    gdcm::FileHelper *fileH = gdcm::FileHelper::New(fileToBuild);
492    //fileH->SetImageData(imageData,size);
493    assert( size == testedDataSize );
494    size = of->str().size();
495    //size = sb->in_avail();
496    std::cerr << "Size JPEG:" << size << std::endl;
497    //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
498    memcpy(imageData, of->str().c_str(), size);
499    fileH->SetImageData(imageData, size);
500    //str::string *s = of->str();
501    //fileH->SetWriteTypeToDcmExplVR();
502    fileH->SetWriteTypeToJPEG(  );
503    if( !fileH->Write(outfilename) )
504      {
505      std::cerr << "Badddd" << std::endl;
506      }
507    //of->close();
508    std::ofstream out("/tmp/jpeg2.jpg");
509    //out.write( of->str(), of
510    //out << of->str(); //rdbuf is faster than going through str()
511    //out.write( (char*)imageData, size);
512    out.write( of->str().c_str(), size);
513    //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] << 
514    //  imageData[8] << imageData[9] << std::endl;
515    //out.rdbuf( *sb );
516    out.close();
517
518    delete of;
519    f->Delete();
520    tested->Delete();
521    fileToBuild->Delete();
522    fileH->Delete();
523
524    return 0;
525 }
526