1 /*=========================================================================
4 Module: $RCSfile: WriteDicomAsJPEG.cxx,v $
6 Date: $Date: 2005/10/19 17:56:57 $
7 Version: $Revision: 1.7 $
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;
45 void EncodeWithoutBasicOffsetTable(std::ostream *fp, int numFrag, JpegVector& v) //, uint32_t length)
47 assert( numFrag == 1);
50 uint16_t group = 0xfffe;
51 uint16_t elem = 0xe000;
52 gdcm::binary_write(*fp, group);
53 gdcm::binary_write(*fp, elem);
55 uint32_t item_length = 0x0000;
56 gdcm::binary_write(*fp, item_length);
58 // back again...First fragment
60 gdcm::binary_write(*fp, group);
61 gdcm::binary_write(*fp, elem);
63 uint32_t dummy = 0x12345678;
64 size_t offset = fp->tellp();
68 gdcm::binary_write(*fp, dummy);
71 void UpdateJpegFragmentSize(std::ostream *fp, JpegVector const &v)
73 JpegVector::const_iterator i;
74 for(i= v.begin(); i!=v.end(); ++i)
76 const JpegPair &jp = *i;
77 fp->seekp( jp.first );
78 gdcm::binary_write(*fp, jp.second );
82 void CloseJpeg(std::ostream *fp, JpegVector &v)
84 // sequence terminator
85 uint16_t group = 0xfffe;
86 uint16_t elem = 0xe000;
87 gdcm::binary_write(*fp, group);
88 gdcm::binary_write(*fp, elem);
90 uint32_t length = 0x0;
91 gdcm::binary_write(*fp, length);
93 // Jpeg is done, now update the frag length
94 UpdateJpegFragmentSize(fp, v);
99 void EncodeWithBasicOffsetTable(std::ostream *fp, int numFrag)
101 (void)fp; (void)numFrag;
104 bool InitializeJpeg(std::ostream *fp, int fragment_size, int image_width, int image_height,
105 int sample_pixel, int quality, struct jpeg_compress_struct &cinfo, int &row_stride)
108 /* This struct contains the JPEG compression parameters and pointers to
109 * working space (which is allocated as needed by the JPEG library).
110 * It is possible to have several such structures, representing multiple
111 * compression/decompression processes, in existence at once. We refer
112 * to any one struct (and its associated working data) as a "JPEG object".
114 //struct jpeg_compress_struct cinfo;
115 /* This struct represents a JPEG error handler. It is declared separately
116 * because applications often want to supply a specialized error handler
117 * (see the second half of this file for an example). But here we just
118 * take the easy way out and use the standard error handler, which will
119 * print a message on stderr and call exit() if compression fails.
120 * Note that this struct must live as long as the main JPEG parameter
121 * struct, to avoid dangling-pointer problems.
123 struct jpeg_error_mgr jerr;
126 /* Step 1: allocate and initialize JPEG compression object */
128 /* We have to set up the error handler first, in case the initialization
129 * step fails. (Unlikely, but it could happen if you are out of memory.)
130 * This routine fills in the contents of struct jerr, and returns jerr's
131 * address which we place into the link field in cinfo.
133 cinfo.err = jpeg_std_error(&jerr);
134 /* Now we can initialize the JPEG compression object. */
135 jpeg_create_compress(&cinfo);
137 /* Step 2: specify data destination (eg, a file) */
138 /* Note: steps 2 and 3 can be done in either order. */
140 jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
142 /* Step 3: set parameters for compression */
144 /* First we supply a description of the input image.
145 * Four fields of the cinfo struct must be filled in:
147 cinfo.image_width = image_width;/* image width and height, in pixels */
148 cinfo.image_height = image_height;
149 if ( sample_pixel == 3 )
151 cinfo.input_components = 3; /* # of color components per pixel */
152 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
156 cinfo.input_components = 1; /* # of color components per pixel */
157 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
159 /* Now use the library's routine to set default compression parameters.
160 * (You must set at least cinfo.in_color_space before calling this,
161 * since the defaults depend on the source color space.)
163 jpeg_set_defaults(&cinfo);
164 /* Now you can set any non-default parameters you wish to.
165 * Here we just illustrate the use of quality (quantization table) scaling:
167 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
169 /* Step 4: Start compressor */
171 /* TRUE ensures that we will write a complete interchange-JPEG file.
172 * Pass TRUE unless you are very sure of what you're doing.
174 jpeg_start_compress(&cinfo, TRUE);
176 /* Step 5: while (scan lines remain to be written) */
177 /* jpeg_write_scanlines(...); */
179 /* Here we use the library's state variable cinfo.next_scanline as the
180 * loop counter, so that we don't have to keep track ourselves.
181 * To keep things simple, we pass one scanline per call; you can pass
182 * more if you wish, though.
184 if (sample_pixel == 3)
186 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
190 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
193 /* everything was ok */
197 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
199 /* Step 6: Finish compression */
201 jpeg_finish_compress(&cinfo);
203 /* Step 7: release JPEG compression object */
205 /* This is an important step since it will release a good deal of memory. */
206 jpeg_destroy_compress(&cinfo);
208 /* And we're done! */
212 // If false then suspension return
213 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
215 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
216 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
217 row_pointer[0] = image_buffer;
219 while (cinfo.next_scanline < cinfo.image_height) {
220 /* jpeg_write_scanlines expects an array of pointers to scanlines.
221 * Here the array is only one element long, but you could pass
222 * more than one scanline at a time if that's more convenient.
224 //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
226 if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
228 //entering suspension mode, basically we wrote the whole jpeg fragment
229 // technically we could enforce that by checkig the value of row_pointer to
230 // actually be at the end of the image...TODO
233 row_pointer[0] += row_stride;
236 // Well looks like we are done writting the scanlines
240 // input_buffer is ONE image
241 // fragment_size is the size of this image (fragment)
242 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
243 int image_width, int image_height, int sample_pixel, int quality, JpegVector &v)
245 struct jpeg_compress_struct cinfo;
246 int row_stride; /* physical row width in image buffer */
247 bool r = InitializeJpeg(fp, fragment_size, image_width, image_height,
248 sample_pixel, quality, cinfo, row_stride);
251 r = WriteScanlines(cinfo, input_buffer, row_stride);
254 r = FinalizeJpeg(cinfo);
263 // Open a dicom file and compress it as JPEG stream
264 int main(int argc, char *argv[])
269 std::string filename = argv[1];
271 // Step 1 : Create the header of the image
272 gdcm::File *f = new gdcm::File();
273 f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
274 f->SetFileName( filename );
277 gdcm::FileHelper *tested = new gdcm::FileHelper( f );
278 std::string PixelType = tested->GetFile()->GetPixelType();
279 int xsize = f->GetXSize();
280 int ysize = f->GetYSize();
282 int samplesPerPixel = f->GetSamplesPerPixel();
283 size_t testedDataSize = tested->GetImageDataSize();
284 std::cerr << "testedDataSize:" << testedDataSize << std::endl;
285 uint8_t *testedImageData = tested->GetImageData();
287 //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
288 std::ostringstream *of = new std::ostringstream();
289 std::cout << "X: " << xsize << std::endl;
290 std::cout << "Y: " << ysize << std::endl;
291 std::cout << "Sample: " << samplesPerPixel << std::endl;
292 int fragment_size = xsize*ysize*samplesPerPixel;
294 JpegVector JpegFragmentSize;
295 //EncodeWithoutBasicOffsetTable(of, 1, 15328);
296 EncodeWithoutBasicOffsetTable(of, 1, JpegFragmentSize); //, 15328);
297 CreateOneFrame(of, testedImageData, fragment_size, xsize, ysize, samplesPerPixel, 100, JpegFragmentSize);
298 CloseJpeg(of, JpegFragmentSize);
300 if( !f->IsReadable() )
302 std::cerr << "-------------------------------\n"
303 << "Error while creating the file\n"
304 << "This file is considered to be not readable\n";
308 std::streambuf* sb = of->rdbuf();
316 // Step 1 : Create the header of the image
318 gdcm::File *fileToBuild = new gdcm::File();
319 std::ostringstream str;
321 // Set the image size
324 fileToBuild->InsertEntryString(str.str(),0x0028,0x0011); // Columns
327 fileToBuild->InsertEntryString(str.str(),0x0028,0x0010); // Rows
333 // fileToBuild->InsertEntryString(str.str(),0x0028,0x0008); // Number of Frames
336 // Set the pixel type
338 str << 8; //img.componentSize;
339 fileToBuild->InsertEntryString(str.str(),0x0028,0x0100); // Bits Allocated
342 str << 8; //img.componentUse;
343 fileToBuild->InsertEntryString(str.str(),0x0028,0x0101); // Bits Stored
346 str << 7; //( img.componentSize - 1 );
347 fileToBuild->InsertEntryString(str.str(),0x0028,0x0102); // High Bit
349 // Set the pixel representation
351 str << 0; //img.sign;
352 fileToBuild->InsertEntryString(str.str(),0x0028,0x0103); // Pixel Representation
354 // Set the samples per pixel
356 str << samplesPerPixel; //img.components;
357 fileToBuild->InsertEntryString(str.str(),0x0028,0x0002); // Samples per Pixel
359 // Step 2 : Create the output image
360 // std::cout << "2...";
361 // if( img.componentSize%8 > 0 )
363 // img.componentSize += 8-img.componentSize%8;
365 size_t size = xsize * ysize * 1 /*Z*/
366 * samplesPerPixel /* * img.componentSize / 8*/;
368 uint8_t *imageData = new uint8_t[size];
369 gdcm::FileHelper *fileH = new gdcm::FileHelper(fileToBuild);
370 //fileH->SetImageData(imageData,size);
371 assert( size == testedDataSize );
372 size = of->str().size();
373 //size = sb->in_avail();
374 std::cerr << "Size JPEG:" << size << std::endl;
375 //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
376 memcpy(imageData, of->str().c_str(), size);
377 fileH->SetImageData(imageData, size);
378 //str::string *s = of->str();
379 //fileH->SetWriteTypeToDcmExplVR();
380 fileH->SetWriteTypeToJPEG( );
381 std::string fileName = "/tmp/bla.dcm";
382 if( !fileH->Write(fileName) )
384 std::cerr << "Badddd" << std::endl;
387 std::ofstream out("/tmp/jpeg2.jpg");
388 //out.write( of->str(), of
389 //out << of->str(); //rdbuf is faster than going through str()
390 //out.write( (char*)imageData, size);
391 out.write( of->str().c_str(), size);
392 //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] <<
393 // imageData[8] << imageData[9] << std::endl;