1 /*=========================================================================
4 Module: $RCSfile: WriteDicomAsJPEG.cxx,v $
6 Date: $Date: 2006/01/27 10:03:23 $
7 Version: $Revision: 1.10 $
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 #if defined(__BORLANDC__)
35 #include <mem.h> // for memcpy
38 #include "gdcmJPEGFragment.h"
42 #include "jdatasrc.cxx"
43 #include "jdatadst.cxx"
45 typedef std::pair<size_t, uint32_t> JpegPair; //offset, jpeg size
46 typedef std::vector<JpegPair> JpegVector;
48 void WriteDICOMItems(std::ostream *fp, JpegVector &v)
51 uint16_t group = 0xfffe;
52 uint16_t elem = 0xe000;
53 gdcm::binary_write(*fp, group);
54 gdcm::binary_write(*fp, elem);
56 uint32_t dummy = 0x12345678;
57 size_t offset = fp->tellp();
61 gdcm::binary_write(*fp, dummy);
65 void EncodeWithoutBasicOffsetTable(std::ostream *fp, int numFrag)// JpegVector& v) //, uint32_t length)
67 assert( numFrag == 1);
70 uint16_t group = 0xfffe;
71 uint16_t elem = 0xe000;
72 gdcm::binary_write(*fp, group);
73 gdcm::binary_write(*fp, elem);
75 uint32_t item_length = 0x0000;
76 gdcm::binary_write(*fp, item_length);
81 void EncodeWithBasicOffsetTable(std::ostream *fp, int numFrag, size_t &start)
84 uint16_t group = 0xfffe;
85 uint16_t elem = 0xe000;
86 gdcm::binary_write(*fp, group);
87 gdcm::binary_write(*fp, elem);
89 uint32_t item_length = numFrag*4; // sizeof(uint32_t)
90 gdcm::binary_write(*fp, item_length);
92 // Just prepare the space
93 start = fp->tellp(); //to be able to rewind
94 for(int i=0; i<numFrag;++i)
96 uint32_t dummy = 0x0000;
97 gdcm::binary_write(*fp, dummy);
101 void UpdateBasicOffsetTable(std::ostream *fp, JpegVector const &v, size_t pos)
103 JpegVector::const_iterator i;
105 const JpegPair &first = v[0];
106 for(i=v.begin(); i!=v.end(); ++i)
108 const JpegPair &jp = *i;
109 if(i == v.begin() ){ assert( jp.first - first.first == 0); }
110 gdcm::binary_write(*fp, jp.first - first.first);
111 std::cerr << "Updating Table:" << jp.first - first.first << std::endl;
115 void UpdateJpegFragmentSize(std::ostream *fp, JpegVector const &v)
117 JpegVector::const_iterator i;
118 for(i= v.begin(); i!=v.end(); ++i)
120 const JpegPair &jp = *i;
121 fp->seekp( jp.first );
122 gdcm::binary_write(*fp, jp.second );
123 std::cerr << "Updating:" << jp.first << "," << jp.second << std::endl;
127 void CloseJpeg(std::ostream *fp, JpegVector &v)
129 // sequence terminator
130 uint16_t group = 0xfffe;
131 uint16_t elem = 0xe000;
132 gdcm::binary_write(*fp, group);
133 gdcm::binary_write(*fp, elem);
135 uint32_t length = 0x0;
136 gdcm::binary_write(*fp, length);
138 // Jpeg is done, now update the frag length
139 UpdateJpegFragmentSize(fp, v);
142 bool InitializeJpeg(std::ostream *fp, int fragment_size, int image_width, int image_height,
143 int sample_pixel, int quality, struct jpeg_compress_struct &cinfo, int &row_stride)
146 /* This struct contains the JPEG compression parameters and pointers to
147 * working space (which is allocated as needed by the JPEG library).
148 * It is possible to have several such structures, representing multiple
149 * compression/decompression processes, in existence at once. We refer
150 * to any one struct (and its associated working data) as a "JPEG object".
152 //struct jpeg_compress_struct cinfo;
153 /* This struct represents a JPEG error handler. It is declared separately
154 * because applications often want to supply a specialized error handler
155 * (see the second half of this file for an example). But here we just
156 * take the easy way out and use the standard error handler, which will
157 * print a message on stderr and call exit() if compression fails.
158 * Note that this struct must live as long as the main JPEG parameter
159 * struct, to avoid dangling-pointer problems.
161 struct jpeg_error_mgr jerr;
164 /* Step 1: allocate and initialize JPEG compression object */
166 /* We have to set up the error handler first, in case the initialization
167 * step fails. (Unlikely, but it could happen if you are out of memory.)
168 * This routine fills in the contents of struct jerr, and returns jerr's
169 * address which we place into the link field in cinfo.
171 cinfo.err = jpeg_std_error(&jerr);
172 /* Now we can initialize the JPEG compression object. */
173 jpeg_create_compress(&cinfo);
175 /* Step 2: specify data destination (eg, a file) */
176 /* Note: steps 2 and 3 can be done in either order. */
178 jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
180 /* Step 3: set parameters for compression */
182 /* First we supply a description of the input image.
183 * Four fields of the cinfo struct must be filled in:
185 cinfo.image_width = image_width;/* image width and height, in pixels */
186 cinfo.image_height = image_height;
187 if ( sample_pixel == 3 )
189 cinfo.input_components = 3; /* # of color components per pixel */
190 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
194 cinfo.input_components = 1; /* # of color components per pixel */
195 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
197 /* Now use the library's routine to set default compression parameters.
198 * (You must set at least cinfo.in_color_space before calling this,
199 * since the defaults depend on the source color space.)
201 jpeg_set_defaults(&cinfo);
203 * http://www.koders.com/c/fid80DBBF1D49D004EF71CE7C493C34610C4F17D3D3.aspx
204 * http://studio.imagemagick.org/pipermail/magick-users/2002-September/004685.html
205 * You need to set -quality 101 or greater. If quality is 100 or less you
206 * get regular JPEG output. This is not explained in the documentation, only
207 * in the comments in coder/jpeg.c. When you have configured libjpeg with
208 * lossless support, then
210 * quality=predictor*100 + point_transform
212 * If you don't know what these values should be, just use 101.
213 * They only affect the compression ratio, not the image appearance,
216 jpeg_simple_lossless (&cinfo, 1, 1);
217 /* Now you can set any non-default parameters you wish to.
218 * Here we just illustrate the use of quality (quantization table) scaling:
220 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
222 /* Step 4: Start compressor */
224 /* TRUE ensures that we will write a complete interchange-JPEG file.
225 * Pass TRUE unless you are very sure of what you're doing.
227 jpeg_start_compress(&cinfo, TRUE);
229 /* Step 5: while (scan lines remain to be written) */
230 /* jpeg_write_scanlines(...); */
232 /* Here we use the library's state variable cinfo.next_scanline as the
233 * loop counter, so that we don't have to keep track ourselves.
234 * To keep things simple, we pass one scanline per call; you can pass
235 * more if you wish, though.
237 if (sample_pixel == 3)
239 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
243 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
246 /* everything was ok */
250 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
252 /* Step 6: Finish compression */
254 jpeg_finish_compress(&cinfo);
256 /* Step 7: release JPEG compression object */
258 /* This is an important step since it will release a good deal of memory. */
259 jpeg_destroy_compress(&cinfo);
261 /* And we're done! */
265 // If false then suspension return
266 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
268 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
269 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
270 row_pointer[0] = image_buffer;
272 while (cinfo.next_scanline < cinfo.image_height) {
273 /* jpeg_write_scanlines expects an array of pointers to scanlines.
274 * Here the array is only one element long, but you could pass
275 * more than one scanline at a time if that's more convenient.
277 //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
279 if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
281 //entering suspension mode, basically we wrote the whole jpeg fragment
282 // technically we could enforce that by checkig the value of row_pointer to
283 // actually be at the end of the image...TODO
286 row_pointer[0] += row_stride;
289 // Well looks like we are done writting the scanlines
293 // input_buffer is ONE image
294 // fragment_size is the size of this image (fragment)
295 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
296 int image_width, int image_height, int numZ, int sample_pixel, int quality, JpegVector &v)
298 struct jpeg_compress_struct cinfo;
299 int row_stride; /* physical row width in image buffer */
300 size_t beg = fp->tellp();
301 bool r = InitializeJpeg(fp, fragment_size, image_width, image_height,
302 sample_pixel, quality, cinfo, row_stride);
306 uint8_t *pbuffer = (uint8_t*)input_buffer;
308 //for(i=0; i<numZ; ++i)
310 r = WriteScanlines(cinfo, pbuffer, row_stride);
312 // pbuffer+=fragment_size; //shift to next image
315 // size_t end = fp->tellp();
316 // std::cerr << "DIFF: " << end-beg << std::endl;
318 // JpegPair &jp = v[i];
319 // jp.second = end-beg;
323 r = FinalizeJpeg(cinfo);
325 size_t end = fp->tellp();
329 std::cerr << "DIFF: " << i <<" -> " << end-beg << std::endl;
332 //JpegPair &jp = v[0];
338 //bool CreateMultipleFrames (std::ostream *fp, void *input_buffer, int fragment_size,
339 // int image_width, int image_height, int sample_pixel, int quality, JpegVector &v)
343 #define WITHOFFSETTABLE 1
345 // Open a dicom file and compress it as JPEG stream
346 int main(int argc, char *argv[])
351 std::string filename = argv[1];
352 std::string outfilename = "/tmp/bla.dcm";
354 outfilename = argv[2];
357 quality = atoi(argv[2]);
358 std::cerr << "Using quality: " << quality << std::endl;
360 // Step 1 : Create the header of the image
361 gdcm::File *f = gdcm::File::New();
362 f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
363 f->SetFileName( filename );
366 gdcm::FileHelper *tested = gdcm::FileHelper::New( f );
367 std::string PixelType = tested->GetFile()->GetPixelType();
368 int xsize = f->GetXSize();
369 int ysize = f->GetYSize();
370 int zsize = f->GetZSize();
372 int samplesPerPixel = f->GetSamplesPerPixel();
373 size_t testedDataSize = tested->GetImageDataSize();
374 std::cerr << "testedDataSize:" << testedDataSize << std::endl;
375 uint8_t *testedImageData = tested->GetImageData();
377 //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
378 std::ostringstream *of = new std::ostringstream();
379 std::cout << "X: " << xsize << std::endl;
380 std::cout << "Y: " << ysize << std::endl;
381 std::cout << "Sample: " << samplesPerPixel << std::endl;
382 int fragment_size = xsize*ysize*samplesPerPixel;
384 JpegVector JpegFragmentSize;
386 size_t bots; //basic offset table start
387 EncodeWithBasicOffsetTable(of, zsize, bots);
389 EncodeWithoutBasicOffsetTable(of, 1);
391 uint8_t *pImageData = testedImageData;
392 for(int i=0; i<zsize;i++)
394 WriteDICOMItems(of, JpegFragmentSize);
395 CreateOneFrame(of, pImageData, fragment_size, xsize, ysize, zsize,
396 samplesPerPixel, quality, JpegFragmentSize);
397 pImageData += fragment_size;
399 CloseJpeg(of, JpegFragmentSize);
401 UpdateBasicOffsetTable(of, JpegFragmentSize, bots);
404 if( !f->IsReadable() )
406 std::cerr << "-------------------------------\n"
407 << "Error while creating the file\n"
408 << "This file is considered to be not readable\n";
412 std::streambuf* sb = of->rdbuf();
415 // Let save the file as jpeg standalone
417 std::ofstream *jof = new std::ofstream( "/tmp/test.jpg" );
418 CreateOneFrame(jof, testedImageData, fragment_size, xsize, ysize, zsize,
419 samplesPerPixel, 70, JpegFragmentSize);
428 // Step 1 : Create the header of the image
430 gdcm::File *fileToBuild = gdcm::File::New();
431 std::ostringstream str;
433 // Set the image size
436 fileToBuild->InsertEntryString(str.str(),0x0028,0x0011); // Columns
439 fileToBuild->InsertEntryString(str.str(),0x0028,0x0010); // Rows
445 fileToBuild->InsertEntryString(str.str(),0x0028,0x0008); // Number of Frames
448 // Set the pixel type
450 str << 8; //img.componentSize;
451 fileToBuild->InsertEntryString(str.str(),0x0028,0x0100); // Bits Allocated
454 str << 8; //img.componentUse;
455 fileToBuild->InsertEntryString(str.str(),0x0028,0x0101); // Bits Stored
458 str << 7; //( img.componentSize - 1 );
459 fileToBuild->InsertEntryString(str.str(),0x0028,0x0102); // High Bit
461 // Set the pixel representation
463 str << 0; //img.sign;
464 fileToBuild->InsertEntryString(str.str(),0x0028,0x0103); // Pixel Representation
466 // Set the samples per pixel
468 str << samplesPerPixel; //img.components;
469 fileToBuild->InsertEntryString(str.str(),0x0028,0x0002); // Samples per Pixel
471 // Step 2 : Create the output image
472 // std::cout << "2...";
473 // if( img.componentSize%8 > 0 )
475 // img.componentSize += 8-img.componentSize%8;
477 size_t size = xsize * ysize * zsize
478 * samplesPerPixel /* * img.componentSize / 8*/;
480 uint8_t *imageData = new uint8_t[size];
481 gdcm::FileHelper *fileH = gdcm::FileHelper::New(fileToBuild);
482 //fileH->SetImageData(imageData,size);
483 assert( size == testedDataSize );
484 size = of->str().size();
485 //size = sb->in_avail();
486 std::cerr << "Size JPEG:" << size << std::endl;
487 //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
488 memcpy(imageData, of->str().c_str(), size);
489 fileH->SetImageData(imageData, size);
490 //str::string *s = of->str();
491 //fileH->SetWriteTypeToDcmExplVR();
492 fileH->SetWriteTypeToJPEG( );
493 if( !fileH->Write(outfilename) )
495 std::cerr << "Badddd" << std::endl;
498 std::ofstream out("/tmp/jpeg2.jpg");
499 //out.write( of->str(), of
500 //out << of->str(); //rdbuf is faster than going through str()
501 //out.write( (char*)imageData, size);
502 out.write( of->str().c_str(), size);
503 //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] <<
504 // imageData[8] << imageData[9] << std::endl;
511 fileToBuild->Delete();