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