]> Creatis software - gdcm.git/blob - Example/WriteDicomAsJPEG.cxx
ENH: Still cleaning up stuff
[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 17:56:57 $
7   Version:   $Revision: 1.7 $
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 // PS 3.5, page 66
45 void EncodeWithoutBasicOffsetTable(std::ostream *fp, int numFrag, JpegVector& v) //, uint32_t length)
46 {
47   assert( numFrag == 1);
48
49   // Item tag:
50   uint16_t group = 0xfffe;
51   uint16_t elem  = 0xe000;
52   gdcm::binary_write(*fp, group);
53   gdcm::binary_write(*fp, elem);
54   // Item Length
55   uint32_t item_length = 0x0000;
56   gdcm::binary_write(*fp, item_length);
57
58   // back again...First fragment
59   // Item tag:
60   gdcm::binary_write(*fp, group);
61   gdcm::binary_write(*fp, elem);
62   // Item Length
63   uint32_t dummy = 0x12345678;
64   size_t offset = fp->tellp();
65   JpegPair jp;
66   jp.first = offset;
67   v.push_back(jp);
68   gdcm::binary_write(*fp, dummy);
69 }
70
71 void UpdateJpegFragmentSize(std::ostream *fp, JpegVector const &v)
72 {
73   JpegVector::const_iterator i;
74   for(i= v.begin(); i!=v.end(); ++i)
75     {
76     const JpegPair &jp = *i;
77     fp->seekp( jp.first );
78     gdcm::binary_write(*fp, jp.second );
79     }
80 }
81
82 void CloseJpeg(std::ostream *fp, JpegVector &v)
83 {
84   // sequence terminator
85   uint16_t group = 0xfffe;
86   uint16_t elem  = 0xe000;
87   gdcm::binary_write(*fp, group);
88   gdcm::binary_write(*fp, elem);
89
90   uint32_t length = 0x0;
91   gdcm::binary_write(*fp, length);
92
93   // Jpeg is done, now update the frag length
94   UpdateJpegFragmentSize(fp, v);
95 }
96
97
98 // PS 3.5, page 67
99 void EncodeWithBasicOffsetTable(std::ostream *fp, int numFrag)
100 {
101   (void)fp; (void)numFrag;
102 }
103
104 bool InitializeJpeg(std::ostream *fp, int fragment_size, int image_width, int image_height, 
105   int sample_pixel, int quality, struct jpeg_compress_struct &cinfo, int &row_stride)
106 {
107
108   /* This struct contains the JPEG compression parameters and pointers to
109    * working space (which is allocated as needed by the JPEG library).
110    * It is possible to have several such structures, representing multiple
111    * compression/decompression processes, in existence at once.  We refer
112    * to any one struct (and its associated working data) as a "JPEG object".
113    */
114   //struct jpeg_compress_struct cinfo;
115   /* This struct represents a JPEG error handler.  It is declared separately
116    * because applications often want to supply a specialized error handler
117    * (see the second half of this file for an example).  But here we just
118    * take the easy way out and use the standard error handler, which will
119    * print a message on stderr and call exit() if compression fails.
120    * Note that this struct must live as long as the main JPEG parameter
121    * struct, to avoid dangling-pointer problems.
122    */
123   struct jpeg_error_mgr jerr;
124   /* More stuff */
125
126   /* Step 1: allocate and initialize JPEG compression object */
127
128   /* We have to set up the error handler first, in case the initialization
129    * step fails.  (Unlikely, but it could happen if you are out of memory.)
130    * This routine fills in the contents of struct jerr, and returns jerr's
131    * address which we place into the link field in cinfo.
132    */
133   cinfo.err = jpeg_std_error(&jerr);
134   /* Now we can initialize the JPEG compression object. */
135   jpeg_create_compress(&cinfo);
136
137   /* Step 2: specify data destination (eg, a file) */
138   /* Note: steps 2 and 3 can be done in either order. */
139
140   jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
141
142   /* Step 3: set parameters for compression */
143
144   /* First we supply a description of the input image.
145    * Four fields of the cinfo struct must be filled in:
146    */
147   cinfo.image_width = image_width;/* image width and height, in pixels */
148   cinfo.image_height = image_height;
149   if ( sample_pixel == 3 )
150     {
151     cinfo.input_components = 3;     /* # of color components per pixel */
152     cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
153     }
154   else
155     {
156     cinfo.input_components = 1;     /* # of color components per pixel */
157     cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
158     }
159   /* Now use the library's routine to set default compression parameters.
160    * (You must set at least cinfo.in_color_space before calling this,
161    * since the defaults depend on the source color space.)
162    */
163   jpeg_set_defaults(&cinfo);
164   /* Now you can set any non-default parameters you wish to.
165    * Here we just illustrate the use of quality (quantization table) scaling:
166    */
167   jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
168
169   /* Step 4: Start compressor */
170
171   /* TRUE ensures that we will write a complete interchange-JPEG file.
172    * Pass TRUE unless you are very sure of what you're doing.
173    */
174   jpeg_start_compress(&cinfo, TRUE);
175
176   /* Step 5: while (scan lines remain to be written) */
177   /*           jpeg_write_scanlines(...); */
178
179   /* Here we use the library's state variable cinfo.next_scanline as the
180    * loop counter, so that we don't have to keep track ourselves.
181    * To keep things simple, we pass one scanline per call; you can pass
182    * more if you wish, though.
183    */
184   if (sample_pixel == 3)
185     {
186     row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
187     }
188   else
189     {
190     row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
191     }
192
193   /* everything was ok */
194   return true;
195 }
196
197 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
198 {
199   /* Step 6: Finish compression */
200
201   jpeg_finish_compress(&cinfo);
202   
203   /* Step 7: release JPEG compression object */
204
205   /* This is an important step since it will release a good deal of memory. */
206   jpeg_destroy_compress(&cinfo);
207
208   /* And we're done! */
209   return true;
210 }
211
212 // If false then suspension return
213 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
214 {
215   JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
216   JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
217   row_pointer[0] = image_buffer;
218
219   while (cinfo.next_scanline < cinfo.image_height) {
220     /* jpeg_write_scanlines expects an array of pointers to scanlines.
221      * Here the array is only one element long, but you could pass
222      * more than one scanline at a time if that's more convenient.
223      */
224     //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
225
226     if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
227       {
228       //entering suspension mode, basically we wrote the whole jpeg fragment
229       // technically we could enforce that by checkig the value of row_pointer to
230       // actually be at the end of the image...TODO
231       return false;
232       }
233     row_pointer[0] += row_stride;
234   }
235
236   // Well looks like we are done writting the scanlines
237   return true;
238 }
239
240 // input_buffer is ONE image
241 // fragment_size is the size of this image (fragment)
242 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
243                      int image_width, int image_height, int sample_pixel, int quality, JpegVector &v)
244 {
245   struct jpeg_compress_struct cinfo;
246   int row_stride;            /* physical row width in image buffer */
247   bool r = InitializeJpeg(fp, fragment_size, image_width, image_height, 
248       sample_pixel, quality, cinfo, row_stride);
249   assert( r );
250
251   r = WriteScanlines(cinfo, input_buffer, row_stride);
252   assert( r );
253
254   r = FinalizeJpeg(cinfo);
255   assert( r );
256
257   JpegPair &jp = v[0];
258   jp.second = 15328;
259
260   return true;
261 }
262
263 // Open a dicom file and compress it as JPEG stream
264 int main(int argc, char *argv[])
265 {
266   if( argc < 2)
267     return 1;
268
269   std::string filename = argv[1];
270
271 // Step 1 : Create the header of the image
272    gdcm::File *f = new gdcm::File();
273    f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
274    f->SetFileName( filename );
275    f->Load();
276
277    gdcm::FileHelper *tested = new gdcm::FileHelper( f );
278    std::string PixelType = tested->GetFile()->GetPixelType();
279    int xsize = f->GetXSize();
280    int ysize = f->GetYSize();
281
282    int samplesPerPixel = f->GetSamplesPerPixel();
283    size_t testedDataSize    = tested->GetImageDataSize();
284    std::cerr << "testedDataSize:" << testedDataSize << std::endl;
285    uint8_t *testedImageData = tested->GetImageData();
286
287    //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
288    std::ostringstream *of = new std::ostringstream();
289    std::cout << "X: " << xsize << std::endl;
290    std::cout << "Y: " << ysize << std::endl;
291    std::cout << "Sample: " << samplesPerPixel << std::endl;
292    int fragment_size = xsize*ysize*samplesPerPixel;
293
294    JpegVector JpegFragmentSize;
295    //EncodeWithoutBasicOffsetTable(of, 1, 15328);
296    EncodeWithoutBasicOffsetTable(of, 1, JpegFragmentSize); //, 15328);
297    CreateOneFrame(of, testedImageData, fragment_size, xsize, ysize, samplesPerPixel, 100, JpegFragmentSize);
298    CloseJpeg(of, JpegFragmentSize);
299
300    if( !f->IsReadable() )
301    {
302       std::cerr << "-------------------------------\n"
303                 << "Error while creating the file\n"
304                 << "This file is considered to be not readable\n";
305
306       return 1;
307    }
308    std::streambuf* sb = of->rdbuf();
309    (void)sb;
310
311
312
313
314
315
316 // Step 1 : Create the header of the image
317
318    gdcm::File *fileToBuild = new gdcm::File();
319    std::ostringstream str;
320
321    // Set the image size
322    str.str("");
323    str << xsize;
324    fileToBuild->InsertEntryString(str.str(),0x0028,0x0011); // Columns
325    str.str("");
326    str << ysize;
327    fileToBuild->InsertEntryString(str.str(),0x0028,0x0010); // Rows
328
329    //if(img.sizeZ>1)
330    //{
331    //   str.str("");
332    //   str << img.sizeZ;
333    //   fileToBuild->InsertEntryString(str.str(),0x0028,0x0008); // Number of Frames
334    //}
335
336    // Set the pixel type
337    str.str("");
338    str << 8; //img.componentSize;
339    fileToBuild->InsertEntryString(str.str(),0x0028,0x0100); // Bits Allocated
340
341    str.str("");
342    str << 8; //img.componentUse;
343    fileToBuild->InsertEntryString(str.str(),0x0028,0x0101); // Bits Stored
344
345    str.str("");
346    str << 7; //( img.componentSize - 1 );
347    fileToBuild->InsertEntryString(str.str(),0x0028,0x0102); // High Bit
348
349    // Set the pixel representation
350    str.str("");
351    str << 0; //img.sign;
352    fileToBuild->InsertEntryString(str.str(),0x0028,0x0103); // Pixel Representation
353
354    // Set the samples per pixel
355    str.str("");
356    str << samplesPerPixel; //img.components;
357    fileToBuild->InsertEntryString(str.str(),0x0028,0x0002); // Samples per Pixel
358
359 // Step 2 : Create the output image
360 //   std::cout << "2...";
361 //   if( img.componentSize%8 > 0 )
362 //   {
363 //      img.componentSize += 8-img.componentSize%8;
364 //   }
365    size_t size = xsize * ysize * 1 /*Z*/ 
366                * samplesPerPixel /* * img.componentSize / 8*/;
367
368    uint8_t *imageData = new uint8_t[size];
369    gdcm::FileHelper *fileH = new gdcm::FileHelper(fileToBuild);
370    //fileH->SetImageData(imageData,size);
371    assert( size == testedDataSize );
372    size = of->str().size();
373    //size = sb->in_avail();
374    std::cerr << "Size JPEG:" << size << std::endl;
375    //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
376    memcpy(imageData, of->str().c_str(), size);
377    fileH->SetImageData(imageData, size);
378    //str::string *s = of->str();
379    //fileH->SetWriteTypeToDcmExplVR();
380    fileH->SetWriteTypeToJPEG(  );
381    std::string fileName = "/tmp/bla.dcm";
382    if( !fileH->Write(fileName) )
383      {
384      std::cerr << "Badddd" << std::endl;
385      }
386    //of->close();
387    std::ofstream out("/tmp/jpeg2.jpg");
388    //out.write( of->str(), of
389    //out << of->str(); //rdbuf is faster than going through str()
390    //out.write( (char*)imageData, size);
391    out.write( of->str().c_str(), size);
392    //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] << 
393    //  imageData[8] << imageData[9] << std::endl;
394    //out.rdbuf( *sb );
395    out.close();
396
397    delete of;
398    delete f;
399    delete tested;
400    delete fileToBuild;
401    delete fileH;
402
403    return 0;
404 }
405