1 /*=========================================================================
4 Module: $RCSfile: WriteDicomAsJPEG.cxx,v $
6 Date: $Date: 2005/10/19 16:05:14 $
7 Version: $Revision: 1.5 $
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"
42 void EncodeWithoutBasicOffsetTable(std::ostream *fp, int numFrag, uint32_t length)
44 assert( numFrag == 1);
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 item_length = 0x0000;
53 gdcm::binary_write(*fp, item_length);
55 // back again...First fragment
57 gdcm::binary_write(*fp, group);
58 gdcm::binary_write(*fp, elem);
60 gdcm::binary_write(*fp, length);
64 void CloseJpeg(std::ostream *fp)
66 // sequence terminator
67 uint16_t group = 0xfffe;
68 uint16_t elem = 0xe000;
69 gdcm::binary_write(*fp, group);
70 gdcm::binary_write(*fp, elem);
72 uint32_t length = 0x0;
73 gdcm::binary_write(*fp, length);
77 void EncodeWithBasicOffsetTable(std::ostream *fp, int numFrag)
79 (void)fp; (void)numFrag;
82 bool InitializeJpeg(std::ostream *fp, int fragment_size, int image_width, int image_height,
83 int sample_pixel, int quality, struct jpeg_compress_struct &cinfo, int &row_stride)
86 /* This struct contains the JPEG compression parameters and pointers to
87 * working space (which is allocated as needed by the JPEG library).
88 * It is possible to have several such structures, representing multiple
89 * compression/decompression processes, in existence at once. We refer
90 * to any one struct (and its associated working data) as a "JPEG object".
92 //struct jpeg_compress_struct cinfo;
93 /* This struct represents a JPEG error handler. It is declared separately
94 * because applications often want to supply a specialized error handler
95 * (see the second half of this file for an example). But here we just
96 * take the easy way out and use the standard error handler, which will
97 * print a message on stderr and call exit() if compression fails.
98 * Note that this struct must live as long as the main JPEG parameter
99 * struct, to avoid dangling-pointer problems.
101 struct jpeg_error_mgr jerr;
104 /* Step 1: allocate and initialize JPEG compression object */
106 /* We have to set up the error handler first, in case the initialization
107 * step fails. (Unlikely, but it could happen if you are out of memory.)
108 * This routine fills in the contents of struct jerr, and returns jerr's
109 * address which we place into the link field in cinfo.
111 cinfo.err = jpeg_std_error(&jerr);
112 /* Now we can initialize the JPEG compression object. */
113 jpeg_create_compress(&cinfo);
115 /* Step 2: specify data destination (eg, a file) */
116 /* Note: steps 2 and 3 can be done in either order. */
118 jpeg_stdio_dest(&cinfo, fp, fragment_size, 1);
120 /* Step 3: set parameters for compression */
122 /* First we supply a description of the input image.
123 * Four fields of the cinfo struct must be filled in:
125 cinfo.image_width = image_width;/* image width and height, in pixels */
126 cinfo.image_height = image_height;
127 if ( sample_pixel == 3 )
129 cinfo.input_components = 3; /* # of color components per pixel */
130 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
134 cinfo.input_components = 1; /* # of color components per pixel */
135 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
137 /* Now use the library's routine to set default compression parameters.
138 * (You must set at least cinfo.in_color_space before calling this,
139 * since the defaults depend on the source color space.)
141 jpeg_set_defaults(&cinfo);
142 /* Now you can set any non-default parameters you wish to.
143 * Here we just illustrate the use of quality (quantization table) scaling:
145 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
147 /* Step 4: Start compressor */
149 /* TRUE ensures that we will write a complete interchange-JPEG file.
150 * Pass TRUE unless you are very sure of what you're doing.
152 jpeg_start_compress(&cinfo, TRUE);
154 /* Step 5: while (scan lines remain to be written) */
155 /* jpeg_write_scanlines(...); */
157 /* Here we use the library's state variable cinfo.next_scanline as the
158 * loop counter, so that we don't have to keep track ourselves.
159 * To keep things simple, we pass one scanline per call; you can pass
160 * more if you wish, though.
162 if (sample_pixel == 3)
164 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
168 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
171 /* everything was ok */
175 bool FinalizeJpeg(struct jpeg_compress_struct &cinfo)
177 /* Step 6: Finish compression */
179 jpeg_finish_compress(&cinfo);
181 /* Step 7: release JPEG compression object */
183 /* This is an important step since it will release a good deal of memory. */
184 jpeg_destroy_compress(&cinfo);
186 /* And we're done! */
190 // If false then suspension return
191 bool WriteScanlines(struct jpeg_compress_struct &cinfo, void *input_buffer, int row_stride)
193 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
194 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
195 row_pointer[0] = image_buffer;
197 while (cinfo.next_scanline < cinfo.image_height) {
198 /* jpeg_write_scanlines expects an array of pointers to scanlines.
199 * Here the array is only one element long, but you could pass
200 * more than one scanline at a time if that's more convenient.
202 //row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
204 if( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1)
206 //entering suspension mode, basically we wrote the whole jpeg fragment
210 row_pointer[0] += row_stride;
213 // Well looks like we are done writting the scanlines
217 // input_buffer is ONE image
218 // fragment_size is the size of this image (fragment)
219 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
220 int image_width, int image_height, int sample_pixel, int quality,
223 struct jpeg_compress_struct cinfo;
224 int row_stride; /* physical row width in image buffer */
225 bool r = InitializeJpeg(fp, fragment_size, image_width, image_height,
226 sample_pixel, quality, cinfo, row_stride);
229 r = WriteScanlines(cinfo, input_buffer, row_stride);
232 r = FinalizeJpeg(cinfo);
238 // Open a dicom file and compress it as JPEG stream
239 int main(int argc, char *argv[])
244 std::string filename = argv[1];
246 // Step 1 : Create the header of the image
247 gdcm::File *f = new gdcm::File();
248 f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
249 f->SetFileName( filename );
252 gdcm::FileHelper *tested = new gdcm::FileHelper( f );
253 std::string PixelType = tested->GetFile()->GetPixelType();
254 int xsize = f->GetXSize();
255 int ysize = f->GetYSize();
257 int samplesPerPixel = f->GetSamplesPerPixel();
258 size_t testedDataSize = tested->GetImageDataSize();
259 std::cerr << "testedDataSize:" << testedDataSize << std::endl;
260 uint8_t *testedImageData = tested->GetImageData();
262 //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
263 std::ostringstream *of = new std::ostringstream();
264 std::cout << "X: " << xsize << std::endl;
265 std::cout << "Y: " << ysize << std::endl;
266 std::cout << "Sample: " << samplesPerPixel << std::endl;
267 int fragment_size = xsize*ysize*samplesPerPixel;
269 EncodeWithoutBasicOffsetTable(of, 1, 15328);
271 CreateOneFrame(of, testedImageData, fragment_size, xsize, ysize, samplesPerPixel, 100, suspend);
274 if( !f->IsReadable() )
276 std::cerr << "-------------------------------\n"
277 << "Error while creating the file\n"
278 << "This file is considered to be not readable\n";
282 std::streambuf* sb = of->rdbuf();
290 // Step 1 : Create the header of the image
292 gdcm::File *fileToBuild = new gdcm::File();
293 std::ostringstream str;
295 // Set the image size
298 fileToBuild->InsertEntryString(str.str(),0x0028,0x0011); // Columns
301 fileToBuild->InsertEntryString(str.str(),0x0028,0x0010); // Rows
307 // fileToBuild->InsertEntryString(str.str(),0x0028,0x0008); // Number of Frames
310 // Set the pixel type
312 str << 8; //img.componentSize;
313 fileToBuild->InsertEntryString(str.str(),0x0028,0x0100); // Bits Allocated
316 str << 8; //img.componentUse;
317 fileToBuild->InsertEntryString(str.str(),0x0028,0x0101); // Bits Stored
320 str << 7; //( img.componentSize - 1 );
321 fileToBuild->InsertEntryString(str.str(),0x0028,0x0102); // High Bit
323 // Set the pixel representation
325 str << 0; //img.sign;
326 fileToBuild->InsertEntryString(str.str(),0x0028,0x0103); // Pixel Representation
328 // Set the samples per pixel
330 str << samplesPerPixel; //img.components;
331 fileToBuild->InsertEntryString(str.str(),0x0028,0x0002); // Samples per Pixel
333 // Step 2 : Create the output image
334 // std::cout << "2...";
335 // if( img.componentSize%8 > 0 )
337 // img.componentSize += 8-img.componentSize%8;
339 size_t size = xsize * ysize * 1 /*Z*/
340 * samplesPerPixel /* * img.componentSize / 8*/;
342 uint8_t *imageData = new uint8_t[size];
343 gdcm::FileHelper *fileH = new gdcm::FileHelper(fileToBuild);
344 //fileH->SetImageData(imageData,size);
345 assert( size == testedDataSize );
346 size = of->str().size();
347 //size = sb->in_avail();
348 std::cerr << "Size JPEG:" << size << std::endl;
349 //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
350 memcpy(imageData, of->str().c_str(), size);
351 fileH->SetImageData(imageData, size);
352 //str::string *s = of->str();
353 //fileH->SetWriteTypeToDcmExplVR();
354 fileH->SetWriteTypeToJPEG( );
355 std::string fileName = "/tmp/bla.dcm";
356 if( !fileH->Write(fileName) )
358 std::cerr << "Badddd" << std::endl;
361 std::ofstream out("/tmp/jpeg2.jpg");
362 //out.write( of->str(), of
363 //out << of->str(); //rdbuf is faster than going through str()
364 //out.write( (char*)imageData, size);
365 out.write( of->str().c_str(), size);
366 //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] <<
367 // imageData[8] << imageData[9] << std::endl;