]> Creatis software - gdcm.git/blob - Example/WriteDicomAsJPEG.cxx
Add #include for BCC.
[gdcm.git] / Example / WriteDicomAsJPEG.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: WriteDicomAsJPEG.cxx,v $
5   Language:  C++
6   Date:      $Date: 2006/01/27 10:03:23 $
7   Version:   $Revision: 1.10 $
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     row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
240     }
241   else
242     {
243     row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
244     }
245
246   /* everything was ok */
247   return true;
248 }
249
250 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
251 {
252   /* Step 6: Finish compression */
253
254   jpeg_finish_compress(&cinfo);
255   
256   /* Step 7: release JPEG compression object */
257
258   /* This is an important step since it will release a good deal of memory. */
259   jpeg_destroy_compress(&cinfo);
260
261   /* And we're done! */
262   return true;
263 }
264
265 // If false then suspension return
266 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
267 {
268   JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
269   JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
270   row_pointer[0] = image_buffer;
271
272   while (cinfo.next_scanline < cinfo.image_height) {
273     /* jpeg_write_scanlines expects an array of pointers to scanlines.
274      * Here the array is only one element long, but you could pass
275      * more than one scanline at a time if that's more convenient.
276      */
277     //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
278
279     if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
280       {
281       //entering suspension mode, basically we wrote the whole jpeg fragment
282       // technically we could enforce that by checkig the value of row_pointer to
283       // actually be at the end of the image...TODO
284       return false;
285       }
286     row_pointer[0] += row_stride;
287   }
288
289   // Well looks like we are done writting the scanlines
290   return true;
291 }
292
293 // input_buffer is ONE image
294 // fragment_size is the size of this image (fragment)
295 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
296                      int image_width, int image_height, int numZ, int sample_pixel, int quality, JpegVector &v)
297 {
298   struct jpeg_compress_struct cinfo;
299   int row_stride;            /* physical row width in image buffer */
300   size_t beg = fp->tellp();
301   bool r = InitializeJpeg(fp, fragment_size, image_width, image_height, 
302       sample_pixel, quality, cinfo, row_stride);
303   assert( r );
304   (void)numZ;
305
306   uint8_t *pbuffer = (uint8_t*)input_buffer;
307   //int i;
308   //for(i=0; i<numZ; ++i)
309 //    {
310     r = WriteScanlines(cinfo, pbuffer, row_stride);
311     assert( r );
312 //    pbuffer+=fragment_size; //shift to next image
313
314     //Upodate frag size
315 //    size_t end = fp->tellp();
316 //    std::cerr << "DIFF: " << end-beg << std::endl;
317
318 //    JpegPair &jp = v[i];
319 //    jp.second = end-beg;
320     //beg = end; //
321  //   }
322
323   r = FinalizeJpeg(cinfo);
324   assert( r );
325     size_t end = fp->tellp();
326     static int i = 0;
327     JpegPair &jp = v[i];
328     jp.second = end-beg;
329     std::cerr << "DIFF: " << i <<" -> " << end-beg << std::endl;
330     ++i;
331
332   //JpegPair &jp = v[0];
333   //jp.second = 15328;
334
335   return true;
336 }
337
338 //bool CreateMultipleFrames (std::ostream *fp, void *input_buffer, int fragment_size,
339 //               int image_width, int image_height, int sample_pixel, int quality, JpegVector &v)
340 //{
341 //}
342
343 #define WITHOFFSETTABLE 1
344
345 // Open a dicom file and compress it as JPEG stream
346 int main(int argc, char *argv[])
347 {
348   if( argc < 2)
349     return 1;
350
351    std::string filename = argv[1];
352    std::string outfilename = "/tmp/bla.dcm";
353    if( argc >= 3 )
354      outfilename = argv[2];
355    int quality = 100;
356    if( argc >= 4 )
357      quality = atoi(argv[2]);
358    std::cerr << "Using quality: " << quality << std::endl;
359
360 // Step 1 : Create the header of the image
361    gdcm::File *f = gdcm::File::New();
362    f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
363    f->SetFileName( filename );
364    f->Load();
365
366    gdcm::FileHelper *tested = gdcm::FileHelper::New( f );
367    std::string PixelType = tested->GetFile()->GetPixelType();
368    int xsize = f->GetXSize();
369    int ysize = f->GetYSize();
370    int zsize = f->GetZSize();
371
372    int samplesPerPixel = f->GetSamplesPerPixel();
373    size_t testedDataSize    = tested->GetImageDataSize();
374    std::cerr << "testedDataSize:" << testedDataSize << std::endl;
375    uint8_t *testedImageData = tested->GetImageData();
376
377    //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
378    std::ostringstream *of = new std::ostringstream();
379    std::cout << "X: " << xsize << std::endl;
380    std::cout << "Y: " << ysize << std::endl;
381    std::cout << "Sample: " << samplesPerPixel << std::endl;
382    int fragment_size = xsize*ysize*samplesPerPixel;
383
384    JpegVector JpegFragmentSize;
385 #if WITHOFFSETTABLE
386    size_t bots; //basic offset table start
387    EncodeWithBasicOffsetTable(of, zsize, bots);
388 #else
389    EncodeWithoutBasicOffsetTable(of, 1);
390 #endif
391    uint8_t *pImageData = testedImageData;
392    for(int i=0; i<zsize;i++)
393      {
394      WriteDICOMItems(of, JpegFragmentSize);
395      CreateOneFrame(of, pImageData, fragment_size, xsize, ysize, zsize, 
396        samplesPerPixel, quality, JpegFragmentSize);
397      pImageData += fragment_size;
398      }
399    CloseJpeg(of, JpegFragmentSize);
400 #if WITHOFFSETTABLE
401    UpdateBasicOffsetTable(of, JpegFragmentSize, bots);
402 #endif
403
404    if( !f->IsReadable() )
405    {
406       std::cerr << "-------------------------------\n"
407                 << "Error while creating the file\n"
408                 << "This file is considered to be not readable\n";
409
410       return 1;
411    }
412    std::streambuf* sb = of->rdbuf();
413    (void)sb;
414
415    // Let save the file as jpeg standalone
416      {
417      std::ofstream *jof = new std::ofstream( "/tmp/test.jpg" );
418      CreateOneFrame(jof, testedImageData, fragment_size, xsize, ysize, zsize, 
419        samplesPerPixel, 70, JpegFragmentSize);
420      jof->close();
421      delete jof;
422      }
423
424
425
426
427
428 // Step 1 : Create the header of the image
429
430    gdcm::File *fileToBuild = gdcm::File::New();
431    std::ostringstream str;
432
433    // Set the image size
434    str.str("");
435    str << xsize;
436    fileToBuild->InsertEntryString(str.str(),0x0028,0x0011); // Columns
437    str.str("");
438    str << ysize;
439    fileToBuild->InsertEntryString(str.str(),0x0028,0x0010); // Rows
440
441    if(zsize>1)
442    {
443       str.str("");
444       str << zsize;
445       fileToBuild->InsertEntryString(str.str(),0x0028,0x0008); // Number of Frames
446    }
447
448    // Set the pixel type
449    str.str("");
450    str << 8; //img.componentSize;
451    fileToBuild->InsertEntryString(str.str(),0x0028,0x0100); // Bits Allocated
452
453    str.str("");
454    str << 8; //img.componentUse;
455    fileToBuild->InsertEntryString(str.str(),0x0028,0x0101); // Bits Stored
456
457    str.str("");
458    str << 7; //( img.componentSize - 1 );
459    fileToBuild->InsertEntryString(str.str(),0x0028,0x0102); // High Bit
460
461    // Set the pixel representation
462    str.str("");
463    str << 0; //img.sign;
464    fileToBuild->InsertEntryString(str.str(),0x0028,0x0103); // Pixel Representation
465
466    // Set the samples per pixel
467    str.str("");
468    str << samplesPerPixel; //img.components;
469    fileToBuild->InsertEntryString(str.str(),0x0028,0x0002); // Samples per Pixel
470
471 // Step 2 : Create the output image
472 //   std::cout << "2...";
473 //   if( img.componentSize%8 > 0 )
474 //   {
475 //      img.componentSize += 8-img.componentSize%8;
476 //   }
477    size_t size = xsize * ysize * zsize
478                * samplesPerPixel /* * img.componentSize / 8*/;
479
480    uint8_t *imageData = new uint8_t[size];
481    gdcm::FileHelper *fileH = gdcm::FileHelper::New(fileToBuild);
482    //fileH->SetImageData(imageData,size);
483    assert( size == testedDataSize );
484    size = of->str().size();
485    //size = sb->in_avail();
486    std::cerr << "Size JPEG:" << size << std::endl;
487    //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
488    memcpy(imageData, of->str().c_str(), size);
489    fileH->SetImageData(imageData, size);
490    //str::string *s = of->str();
491    //fileH->SetWriteTypeToDcmExplVR();
492    fileH->SetWriteTypeToJPEG(  );
493    if( !fileH->Write(outfilename) )
494      {
495      std::cerr << "Badddd" << std::endl;
496      }
497    //of->close();
498    std::ofstream out("/tmp/jpeg2.jpg");
499    //out.write( of->str(), of
500    //out << of->str(); //rdbuf is faster than going through str()
501    //out.write( (char*)imageData, size);
502    out.write( of->str().c_str(), size);
503    //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] << 
504    //  imageData[8] << imageData[9] << std::endl;
505    //out.rdbuf( *sb );
506    out.close();
507
508    delete of;
509    f->Delete();
510    tested->Delete();
511    fileToBuild->Delete();
512    fileH->Delete();
513
514    return 0;
515 }
516