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