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