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