]> Creatis software - gdcm.git/blob - Example/WriteDicomAsJPEG.cxx
1681047023b12e10a8bd6bdb41668dcbe3d7c3e5
[gdcm.git] / Example / WriteDicomAsJPEG.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: WriteDicomAsJPEG.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/08/18 16:08:16 $
7   Version:   $Revision: 1.13 $
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     uint32_t offset = jp.first - first.first;
111     gdcm::binary_write(*fp, offset);
112     //std::cerr << "Updating Table:" << jp.first - first.first << std::endl;
113     }
114 }
115
116 void UpdateJpegFragmentSize(std::ostream *fp, JpegVector const &v)
117 {
118   JpegVector::const_iterator i;
119   for(i= v.begin(); i!=v.end(); ++i)
120     {
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;
126     }
127 }
128
129 void CloseJpeg(std::ostream *fp, JpegVector &v)
130 {
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);
136
137   uint32_t length = 0x0;
138   gdcm::binary_write(*fp, length);
139
140   // Jpeg is done, now update the frag length
141   UpdateJpegFragmentSize(fp, v);
142 }
143
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)
146 {
147
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".
153    */
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.
162    */
163   struct jpeg_error_mgr jerr;
164   /* More stuff */
165
166   /* Step 1: allocate and initialize JPEG compression object */
167
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.
172    */
173   cinfo.err = jpeg_std_error(&jerr);
174   /* Now we can initialize the JPEG compression object. */
175   jpeg_create_compress(&cinfo);
176
177   /* Step 2: specify data destination (eg, a file) */
178   /* Note: steps 2 and 3 can be done in either order. */
179
180   jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
181
182   /* Step 3: set parameters for compression */
183
184   /* First we supply a description of the input image.
185    * Four fields of the cinfo struct must be filled in:
186    */
187   cinfo.image_width = image_width;/* image width and height, in pixels */
188   cinfo.image_height = image_height;
189   if ( sample_pixel == 3 )
190     {
191     cinfo.input_components = 3;     /* # of color components per pixel */
192     cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
193     }
194   else
195     {
196     cinfo.input_components = 1;     /* # of color components per pixel */
197     cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
198     }
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.)
202    */
203   jpeg_set_defaults(&cinfo);
204   /*
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
211    * 
212    *    quality=predictor*100 + point_transform
213    * 
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,
216    * which is lossless.
217    */
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:
221    */
222   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
223
224   /* Step 4: Start compressor */
225
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.
228    */
229   jpeg_start_compress(&cinfo, TRUE);
230
231   /* Step 5: while (scan lines remain to be written) */
232   /*           jpeg_write_scanlines(...); */
233
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.
238    */
239   if (sample_pixel == 3)
240     {
241     assert( sample_pixel == 1 );
242     row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
243     }
244   else
245     {
246     row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
247     }
248
249   /* everything was ok */
250   return true;
251 }
252
253 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
254 {
255   /* Step 6: Finish compression */
256
257   jpeg_finish_compress(&cinfo);
258   
259   /* Step 7: release JPEG compression object */
260
261   /* This is an important step since it will release a good deal of memory. */
262   jpeg_destroy_compress(&cinfo);
263
264   /* And we're done! */
265   return true;
266 }
267
268 // If false then suspension return
269 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
270 {
271   JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
272   JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
273   row_pointer[0] = image_buffer;
274
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.
279      */
280     //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
281
282     if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
283       {
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
287       return false;
288       }
289     row_pointer[0] += row_stride;
290   }
291
292   // Well looks like we are done writting the scanlines
293   return true;
294 }
295
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)
300 {
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);
306   assert( r );
307   (void)numZ;
308
309   uint8_t *pbuffer = (uint8_t*)input_buffer;
310   //int i;
311   //for(i=0; i<numZ; ++i)
312 //    {
313     r = WriteScanlines(cinfo, pbuffer, row_stride);
314     assert( r );
315 //    pbuffer+=fragment_size; //shift to next image
316
317     //Upodate frag size
318 //    size_t end = fp->tellp();
319 //    std::cerr << "DIFF: " << end-beg << std::endl;
320
321 //    JpegPair &jp = v[i];
322 //    jp.second = end-beg;
323     //beg = end; //
324  //   }
325
326   r = FinalizeJpeg(cinfo);
327   assert( r );
328     size_t end = fp->tellp();
329     static int i = 0;
330     JpegPair &jp = v[i];
331     jp.second = end-beg;
332     
333     if( ((end-beg) % 2) )
334     {
335        fp->put( '\0' );
336        jp.second += 1;
337     }
338     assert( !(jp.second % 2) );
339     std::cerr << "DIFF: " << i <<" -> " << jp.second << std::endl;    
340        
341     ++i;
342
343   //JpegPair &jp = v[0];
344   //jp.second = 15328;
345
346   return true;
347 }
348
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)
351 //{
352 //}
353
354 #define WITHOFFSETTABLE 1
355
356 // Open a dicom file and compress it as JPEG stream
357 int main(int argc, char *argv[])
358 {
359   if( argc < 2)
360     return 1;
361
362    std::string filename = argv[1];
363    std::string outfilename = "/tmp/bla.dcm";
364    if( argc >= 3 )
365      outfilename = argv[2];
366    int quality = 100;
367    if( argc >= 4 )
368      quality = atoi(argv[2]);
369    std::cerr << "Using quality: " << quality << std::endl;
370
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 );
375    f->Load();
376
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();
382
383    int samplesPerPixel = f->GetSamplesPerPixel();
384    size_t testedDataSize    = tested->GetImageDataSize();
385    std::cerr << "testedDataSize:" << testedDataSize << std::endl;
386    uint8_t *testedImageData = tested->GetImageData();
387
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;
394
395    JpegVector JpegFragmentSize;
396 #if WITHOFFSETTABLE
397    size_t bots; //basic offset table start
398    EncodeWithBasicOffsetTable(of, zsize, bots);
399 #else
400    EncodeWithoutBasicOffsetTable(of, 1);
401 #endif
402    uint8_t *pImageData = testedImageData;
403    for(int i=0; i<zsize;i++)
404      {
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;
410      }
411    CloseJpeg(of, JpegFragmentSize);
412 #if WITHOFFSETTABLE
413    UpdateBasicOffsetTable(of, JpegFragmentSize, bots);
414 #endif
415
416    if( !f->IsReadable() )
417    {
418       std::cerr << "-------------------------------\n"
419                 << "Error while creating the file\n"
420                 << "This file is considered to be not readable\n";
421
422       return 1;
423    }
424    std::streambuf* sb = of->rdbuf();
425    (void)sb;
426
427    // Let save the file as jpeg standalone
428      {
429      std::ofstream *jof = new std::ofstream( "/tmp/test.jpg" );
430      CreateOneFrame(jof, testedImageData, fragment_size, xsize, ysize, zsize, 
431        samplesPerPixel, 70, JpegFragmentSize);
432      jof->close();
433      delete jof;
434      }
435
436
437
438
439
440 // Step 1 : Create the header of the image
441
442    gdcm::File *fileToBuild = gdcm::File::New();
443    std::ostringstream str;
444
445    // Set the image size
446    str.str("");
447    str << xsize;
448    fileToBuild->InsertEntryString(str.str(),0x0028,0x0011,"US"); // Columns
449    str.str("");
450    str << ysize;
451    fileToBuild->InsertEntryString(str.str(),0x0028,0x0010,"US"); // Rows
452
453    if(zsize>1)
454    {
455       str.str("");
456       str << zsize;
457       fileToBuild->InsertEntryString(str.str(),0x0028,0x0008,"IS"); // Number of Frames
458    }
459
460    // Set the pixel type
461    str.str("");
462    str << 8; //img.componentSize;
463    fileToBuild->InsertEntryString(str.str(),0x0028,0x0100,"US"); // Bits Allocated
464
465    str.str("");
466    str << 8; //img.componentUse;
467    fileToBuild->InsertEntryString(str.str(),0x0028,0x0101,"US"); // Bits Stored
468
469    str.str("");
470    str << 7; //( img.componentSize - 1 );
471    fileToBuild->InsertEntryString(str.str(),0x0028,0x0102,"US"); // High Bit
472
473    // Set the pixel representation
474    str.str("");
475    str << 0; //img.sign;
476    fileToBuild->InsertEntryString(str.str(),0x0028,0x0103,"US"); // Pixel Representation
477
478    // Set the samples per pixel
479    str.str("");
480    str << samplesPerPixel; //img.components;
481    fileToBuild->InsertEntryString(str.str(),0x0028,0x0002,"US"); // Samples per Pixel
482
483 // Step 2 : Create the output image
484 //   std::cout << "2...";
485 //   if( img.componentSize%8 > 0 )
486 //   {
487 //      img.componentSize += 8-img.componentSize%8;
488 //   }
489    size_t size = xsize * ysize * zsize
490                * samplesPerPixel /* * img.componentSize / 8*/;
491
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) )
506      {
507      std::cerr << "Badddd" << std::endl;
508      }
509    //of->close();
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;
517    //out.rdbuf( *sb );
518    out.close();
519
520    delete of;
521    f->Delete();
522    tested->Delete();
523    fileToBuild->Delete();
524    fileH->Delete();
525
526    return 0;
527 }
528