1 /*=========================================================================
4 Module: $RCSfile: WriteDicomAsJPEG.cxx,v $
6 Date: $Date: 2005/10/19 22:19:20 $
7 Version: $Revision: 1.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.
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.
17 =========================================================================*/
20 #include "gdcmFileHelper.h"
28 #include "gdcmjpeg/8/jconfig.h"
29 #include "gdcmjpeg/8/jpeglib.h"
30 #include "gdcmjpeg/8/jinclude.h"
31 #include "gdcmjpeg/8/jerror.h"
34 #include "gdcmJPEGFragment.h"
38 #include "jdatasrc.cxx"
39 #include "jdatadst.cxx"
41 typedef std::pair<size_t, uint32_t> JpegPair; //offset, jpeg size
42 typedef std::vector<JpegPair> JpegVector;
44 void WriteDICOMItems(std::ostream *fp, JpegVector &v)
47 uint16_t group = 0xfffe;
48 uint16_t elem = 0xe000;
49 gdcm::binary_write(*fp, group);
50 gdcm::binary_write(*fp, elem);
52 uint32_t dummy = 0x12345678;
53 size_t offset = fp->tellp();
57 gdcm::binary_write(*fp, dummy);
61 void EncodeWithoutBasicOffsetTable(std::ostream *fp, int numFrag)// JpegVector& v) //, uint32_t length)
63 assert( numFrag == 1);
66 uint16_t group = 0xfffe;
67 uint16_t elem = 0xe000;
68 gdcm::binary_write(*fp, group);
69 gdcm::binary_write(*fp, elem);
71 uint32_t item_length = 0x0000;
72 gdcm::binary_write(*fp, item_length);
77 void EncodeWithBasicOffsetTable(std::ostream *fp, int numFrag, size_t &start)
80 uint16_t group = 0xfffe;
81 uint16_t elem = 0xe000;
82 gdcm::binary_write(*fp, group);
83 gdcm::binary_write(*fp, elem);
85 uint32_t item_length = numFrag*4; // sizeof(uint32_t)
86 gdcm::binary_write(*fp, item_length);
88 // Just prepare the space
89 start = fp->tellp(); //to be able to rewind
90 for(int i=0; i<numFrag;++i)
92 uint32_t dummy = 0x0000;
93 gdcm::binary_write(*fp, dummy);
97 void UpdateBasicOffsetTable(std::ostream *fp, JpegVector const &v, size_t pos)
99 JpegVector::const_iterator i;
101 const JpegPair &first = v[0];
102 for(i=v.begin(); i!=v.end(); ++i)
104 const JpegPair &jp = *i;
105 if(i == v.begin() ){ assert( jp.first - first.first == 0); }
106 gdcm::binary_write(*fp, jp.first - first.first);
107 std::cerr << "Updating Table:" << jp.first - first.first << std::endl;
111 void UpdateJpegFragmentSize(std::ostream *fp, JpegVector const &v)
113 JpegVector::const_iterator i;
114 for(i= v.begin(); i!=v.end(); ++i)
116 const JpegPair &jp = *i;
117 fp->seekp( jp.first );
118 gdcm::binary_write(*fp, jp.second );
119 std::cerr << "Updating:" << jp.first << "," << jp.second << std::endl;
123 void CloseJpeg(std::ostream *fp, JpegVector &v)
125 // sequence terminator
126 uint16_t group = 0xfffe;
127 uint16_t elem = 0xe000;
128 gdcm::binary_write(*fp, group);
129 gdcm::binary_write(*fp, elem);
131 uint32_t length = 0x0;
132 gdcm::binary_write(*fp, length);
134 // Jpeg is done, now update the frag length
135 UpdateJpegFragmentSize(fp, v);
138 bool InitializeJpeg(std::ostream *fp, int fragment_size, int image_width, int image_height,
139 int sample_pixel, int quality, struct jpeg_compress_struct &cinfo, int &row_stride)
142 /* This struct contains the JPEG compression parameters and pointers to
143 * working space (which is allocated as needed by the JPEG library).
144 * It is possible to have several such structures, representing multiple
145 * compression/decompression processes, in existence at once. We refer
146 * to any one struct (and its associated working data) as a "JPEG object".
148 //struct jpeg_compress_struct cinfo;
149 /* This struct represents a JPEG error handler. It is declared separately
150 * because applications often want to supply a specialized error handler
151 * (see the second half of this file for an example). But here we just
152 * take the easy way out and use the standard error handler, which will
153 * print a message on stderr and call exit() if compression fails.
154 * Note that this struct must live as long as the main JPEG parameter
155 * struct, to avoid dangling-pointer problems.
157 struct jpeg_error_mgr jerr;
160 /* Step 1: allocate and initialize JPEG compression object */
162 /* We have to set up the error handler first, in case the initialization
163 * step fails. (Unlikely, but it could happen if you are out of memory.)
164 * This routine fills in the contents of struct jerr, and returns jerr's
165 * address which we place into the link field in cinfo.
167 cinfo.err = jpeg_std_error(&jerr);
168 /* Now we can initialize the JPEG compression object. */
169 jpeg_create_compress(&cinfo);
171 /* Step 2: specify data destination (eg, a file) */
172 /* Note: steps 2 and 3 can be done in either order. */
174 jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
176 /* Step 3: set parameters for compression */
178 /* First we supply a description of the input image.
179 * Four fields of the cinfo struct must be filled in:
181 cinfo.image_width = image_width;/* image width and height, in pixels */
182 cinfo.image_height = image_height;
183 if ( sample_pixel == 3 )
185 cinfo.input_components = 3; /* # of color components per pixel */
186 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
190 cinfo.input_components = 1; /* # of color components per pixel */
191 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
193 /* Now use the library's routine to set default compression parameters.
194 * (You must set at least cinfo.in_color_space before calling this,
195 * since the defaults depend on the source color space.)
197 jpeg_set_defaults(&cinfo);
199 * http://www.koders.com/c/fid80DBBF1D49D004EF71CE7C493C34610C4F17D3D3.aspx
200 * http://studio.imagemagick.org/pipermail/magick-users/2002-September/004685.html
201 * You need to set -quality 101 or greater. If quality is 100 or less you
202 * get regular JPEG output. This is not explained in the documentation, only
203 * in the comments in coder/jpeg.c. When you have configured libjpeg with
204 * lossless support, then
206 * quality=predictor*100 + point_transform
208 * If you don't know what these values should be, just use 101.
209 * They only affect the compression ratio, not the image appearance,
212 jpeg_simple_lossless (&cinfo, 1, 1);
213 /* Now you can set any non-default parameters you wish to.
214 * Here we just illustrate the use of quality (quantization table) scaling:
216 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
218 /* Step 4: Start compressor */
220 /* TRUE ensures that we will write a complete interchange-JPEG file.
221 * Pass TRUE unless you are very sure of what you're doing.
223 jpeg_start_compress(&cinfo, TRUE);
225 /* Step 5: while (scan lines remain to be written) */
226 /* jpeg_write_scanlines(...); */
228 /* Here we use the library's state variable cinfo.next_scanline as the
229 * loop counter, so that we don't have to keep track ourselves.
230 * To keep things simple, we pass one scanline per call; you can pass
231 * more if you wish, though.
233 if (sample_pixel == 3)
235 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
239 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
242 /* everything was ok */
246 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
248 /* Step 6: Finish compression */
250 jpeg_finish_compress(&cinfo);
252 /* Step 7: release JPEG compression object */
254 /* This is an important step since it will release a good deal of memory. */
255 jpeg_destroy_compress(&cinfo);
257 /* And we're done! */
261 // If false then suspension return
262 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
264 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
265 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
266 row_pointer[0] = image_buffer;
268 while (cinfo.next_scanline < cinfo.image_height) {
269 /* jpeg_write_scanlines expects an array of pointers to scanlines.
270 * Here the array is only one element long, but you could pass
271 * more than one scanline at a time if that's more convenient.
273 //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
275 if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
277 //entering suspension mode, basically we wrote the whole jpeg fragment
278 // technically we could enforce that by checkig the value of row_pointer to
279 // actually be at the end of the image...TODO
282 row_pointer[0] += row_stride;
285 // Well looks like we are done writting the scanlines
289 // input_buffer is ONE image
290 // fragment_size is the size of this image (fragment)
291 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
292 int image_width, int image_height, int numZ, int sample_pixel, int quality, JpegVector &v)
294 struct jpeg_compress_struct cinfo;
295 int row_stride; /* physical row width in image buffer */
296 size_t beg = fp->tellp();
297 bool r = InitializeJpeg(fp, fragment_size, image_width, image_height,
298 sample_pixel, quality, cinfo, row_stride);
302 uint8_t *pbuffer = (uint8_t*)input_buffer;
304 //for(i=0; i<numZ; ++i)
306 r = WriteScanlines(cinfo, pbuffer, row_stride);
308 // pbuffer+=fragment_size; //shift to next image
311 // size_t end = fp->tellp();
312 // std::cerr << "DIFF: " << end-beg << std::endl;
314 // JpegPair &jp = v[i];
315 // jp.second = end-beg;
319 r = FinalizeJpeg(cinfo);
321 size_t end = fp->tellp();
325 std::cerr << "DIFF: " << i <<" -> " << end-beg << std::endl;
328 //JpegPair &jp = v[0];
334 //bool CreateMultipleFrames (std::ostream *fp, void *input_buffer, int fragment_size,
335 // int image_width, int image_height, int sample_pixel, int quality, JpegVector &v)
339 #define WITHOFFSETTABLE 1
341 // Open a dicom file and compress it as JPEG stream
342 int main(int argc, char *argv[])
347 std::string filename = argv[1];
348 std::string outfilename = "/tmp/bla.dcm";
350 outfilename = argv[2];
353 quality = atoi(argv[2]);
354 std::cerr << "Using quality: " << quality << std::endl;
356 // Step 1 : Create the header of the image
357 gdcm::File *f = new gdcm::File();
358 f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
359 f->SetFileName( filename );
362 gdcm::FileHelper *tested = new gdcm::FileHelper( f );
363 std::string PixelType = tested->GetFile()->GetPixelType();
364 int xsize = f->GetXSize();
365 int ysize = f->GetYSize();
366 int zsize = f->GetZSize();
368 int samplesPerPixel = f->GetSamplesPerPixel();
369 size_t testedDataSize = tested->GetImageDataSize();
370 std::cerr << "testedDataSize:" << testedDataSize << std::endl;
371 uint8_t *testedImageData = tested->GetImageData();
373 //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
374 std::ostringstream *of = new std::ostringstream();
375 std::cout << "X: " << xsize << std::endl;
376 std::cout << "Y: " << ysize << std::endl;
377 std::cout << "Sample: " << samplesPerPixel << std::endl;
378 int fragment_size = xsize*ysize*samplesPerPixel;
380 JpegVector JpegFragmentSize;
382 size_t bots; //basic offset table start
383 EncodeWithBasicOffsetTable(of, zsize, bots);
385 EncodeWithoutBasicOffsetTable(of, 1);
387 uint8_t *pImageData = testedImageData;
388 for(int i=0; i<zsize;i++)
390 WriteDICOMItems(of, JpegFragmentSize);
391 CreateOneFrame(of, pImageData, fragment_size, xsize, ysize, zsize,
392 samplesPerPixel, quality, JpegFragmentSize);
393 pImageData += fragment_size;
395 CloseJpeg(of, JpegFragmentSize);
397 UpdateBasicOffsetTable(of, JpegFragmentSize, bots);
400 if( !f->IsReadable() )
402 std::cerr << "-------------------------------\n"
403 << "Error while creating the file\n"
404 << "This file is considered to be not readable\n";
408 std::streambuf* sb = of->rdbuf();
411 // Let save the file as jpeg standalone
413 std::ofstream *jof = new std::ofstream( "/tmp/test.jpg" );
414 CreateOneFrame(jof, testedImageData, fragment_size, xsize, ysize, zsize,
415 samplesPerPixel, 70, JpegFragmentSize);
424 // Step 1 : Create the header of the image
426 gdcm::File *fileToBuild = new gdcm::File();
427 std::ostringstream str;
429 // Set the image size
432 fileToBuild->InsertEntryString(str.str(),0x0028,0x0011); // Columns
435 fileToBuild->InsertEntryString(str.str(),0x0028,0x0010); // Rows
441 fileToBuild->InsertEntryString(str.str(),0x0028,0x0008); // Number of Frames
444 // Set the pixel type
446 str << 8; //img.componentSize;
447 fileToBuild->InsertEntryString(str.str(),0x0028,0x0100); // Bits Allocated
450 str << 8; //img.componentUse;
451 fileToBuild->InsertEntryString(str.str(),0x0028,0x0101); // Bits Stored
454 str << 7; //( img.componentSize - 1 );
455 fileToBuild->InsertEntryString(str.str(),0x0028,0x0102); // High Bit
457 // Set the pixel representation
459 str << 0; //img.sign;
460 fileToBuild->InsertEntryString(str.str(),0x0028,0x0103); // Pixel Representation
462 // Set the samples per pixel
464 str << samplesPerPixel; //img.components;
465 fileToBuild->InsertEntryString(str.str(),0x0028,0x0002); // Samples per Pixel
467 // Step 2 : Create the output image
468 // std::cout << "2...";
469 // if( img.componentSize%8 > 0 )
471 // img.componentSize += 8-img.componentSize%8;
473 size_t size = xsize * ysize * zsize
474 * samplesPerPixel /* * img.componentSize / 8*/;
476 uint8_t *imageData = new uint8_t[size];
477 gdcm::FileHelper *fileH = new gdcm::FileHelper(fileToBuild);
478 //fileH->SetImageData(imageData,size);
479 assert( size == testedDataSize );
480 size = of->str().size();
481 //size = sb->in_avail();
482 std::cerr << "Size JPEG:" << size << std::endl;
483 //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
484 memcpy(imageData, of->str().c_str(), size);
485 fileH->SetImageData(imageData, size);
486 //str::string *s = of->str();
487 //fileH->SetWriteTypeToDcmExplVR();
488 fileH->SetWriteTypeToJPEG( );
489 if( !fileH->Write(outfilename) )
491 std::cerr << "Badddd" << std::endl;
494 std::ofstream out("/tmp/jpeg2.jpg");
495 //out.write( of->str(), of
496 //out << of->str(); //rdbuf is faster than going through str()
497 //out.write( (char*)imageData, size);
498 out.write( of->str().c_str(), size);
499 //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] <<
500 // imageData[8] << imageData[9] << std::endl;