1 /*=========================================================================
4 Module: $RCSfile: WriteDicomAsJPEG.cxx,v $
6 Date: $Date: 2005/10/18 20:49:59 $
7 Version: $Revision: 1.4 $
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);
45 uint32_t del = 0xffffffff; //data_element_length
46 //gdcm::binary_write(*fp, del);
49 uint16_t group = 0xfffe;
50 uint16_t elem = 0xe000;
51 gdcm::binary_write(*fp, group);
52 gdcm::binary_write(*fp, elem);
54 uint32_t item_length = 0x0000;
55 gdcm::binary_write(*fp, item_length);
57 // back again...First fragment
59 gdcm::binary_write(*fp, group);
60 gdcm::binary_write(*fp, elem);
62 gdcm::binary_write(*fp, length);
66 void CloseJpeg(std::ostream *fp)
68 // sequence terminator
69 uint16_t group = 0xfffe;
70 uint16_t elem = 0xe000;
71 gdcm::binary_write(*fp, group);
72 gdcm::binary_write(*fp, elem);
74 uint32_t length = 0x0;
75 gdcm::binary_write(*fp, length);
79 void EncodeWithBasicOffsetTable(std::ostream *fp, int numFrag)
81 (void)fp; (void)numFrag;
84 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
85 int image_width, int image_height, int sample_pixel, int quality)
87 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
89 /* This struct contains the JPEG compression parameters and pointers to
90 * working space (which is allocated as needed by the JPEG library).
91 * It is possible to have several such structures, representing multiple
92 * compression/decompression processes, in existence at once. We refer
93 * to any one struct (and its associated working data) as a "JPEG object".
95 struct jpeg_compress_struct cinfo;
96 /* This struct represents a JPEG error handler. It is declared separately
97 * because applications often want to supply a specialized error handler
98 * (see the second half of this file for an example). But here we just
99 * take the easy way out and use the standard error handler, which will
100 * print a message on stderr and call exit() if compression fails.
101 * Note that this struct must live as long as the main JPEG parameter
102 * struct, to avoid dangling-pointer problems.
104 struct jpeg_error_mgr jerr;
106 //FILE* outfile; /* target FILE* /
107 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
108 int row_stride; /* physical row width in image buffer */
110 /* Step 1: allocate and initialize JPEG compression object */
112 /* We have to set up the error handler first, in case the initialization
113 * step fails. (Unlikely, but it could happen if you are out of memory.)
114 * This routine fills in the contents of struct jerr, and returns jerr's
115 * address which we place into the link field in cinfo.
117 cinfo.err = jpeg_std_error(&jerr);
118 /* Now we can initialize the JPEG compression object. */
119 jpeg_create_compress(&cinfo);
121 /* Step 2: specify data destination (eg, a file) */
122 /* Note: steps 2 and 3 can be done in either order. */
124 /* Here we use the library-supplied code to send compressed data to a
125 * stdio stream. You can also write your own code to do something else.
126 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
127 * requires it in order to write binary files.
129 // if ((outfile = fopen(filename, "wb")) == NULL) {
130 // fprintf(stderr, "can't open %s\n", filename);
134 jpeg_stdio_dest(&cinfo, fp, fragment_size);
136 /* Step 3: set parameters for compression */
138 /* First we supply a description of the input image.
139 * Four fields of the cinfo struct must be filled in:
141 cinfo.image_width = image_width;/* image width and height, in pixels */
142 cinfo.image_height = image_height;
143 if ( sample_pixel == 3 )
145 cinfo.input_components = 3; /* # of color components per pixel */
146 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
150 cinfo.input_components = 1; /* # of color components per pixel */
151 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
153 /* Now use the library's routine to set default compression parameters.
154 * (You must set at least cinfo.in_color_space before calling this,
155 * since the defaults depend on the source color space.)
157 jpeg_set_defaults(&cinfo);
158 /* Now you can set any non-default parameters you wish to.
159 * Here we just illustrate the use of quality (quantization table) scaling:
161 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
163 /* Step 4: Start compressor */
165 /* TRUE ensures that we will write a complete interchange-JPEG file.
166 * Pass TRUE unless you are very sure of what you're doing.
168 jpeg_start_compress(&cinfo, TRUE);
170 /* Step 5: while (scan lines remain to be written) */
171 /* jpeg_write_scanlines(...); */
173 /* Here we use the library's state variable cinfo.next_scanline as the
174 * loop counter, so that we don't have to keep track ourselves.
175 * To keep things simple, we pass one scanline per call; you can pass
176 * more if you wish, though.
178 if (sample_pixel == 3)
180 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
184 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
188 while (cinfo.next_scanline < cinfo.image_height) {
189 /* jpeg_write_scanlines expects an array of pointers to scanlines.
190 * Here the array is only one element long, but you could pass
191 * more than one scanline at a time if that's more convenient.
193 row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
195 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
198 /* Step 6: Finish compression */
200 jpeg_finish_compress(&cinfo);
202 /* After finish_compress, we can close the output file. */
204 // fclose(fp); --> the caller will close (multiframe treatement)
206 /* Step 7: release JPEG compression object */
208 /* This is an important step since it will release a good deal of memory. */
209 jpeg_destroy_compress(&cinfo);
211 /* And we're done! */
216 // Open a dicom file and compress it as JPEG stream
217 int main(int argc, char *argv[])
222 std::string filename = argv[1];
224 // Step 1 : Create the header of the image
225 gdcm::File *f = new gdcm::File();
226 f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
227 f->SetFileName( filename );
230 gdcm::FileHelper *tested = new gdcm::FileHelper( f );
231 std::string PixelType = tested->GetFile()->GetPixelType();
232 int xsize = f->GetXSize();
233 int ysize = f->GetYSize();
235 int samplesPerPixel = f->GetSamplesPerPixel();
236 size_t testedDataSize = tested->GetImageDataSize();
237 std::cerr << "testedDataSize:" << testedDataSize << std::endl;
238 uint8_t *testedImageData = tested->GetImageData();
240 //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
241 std::ostringstream *of = new std::ostringstream();
242 std::cout << "X: " << xsize << std::endl;
243 std::cout << "Y: " << ysize << std::endl;
244 std::cout << "Sample: " << samplesPerPixel << std::endl;
245 int fragment_size = xsize*ysize*samplesPerPixel;
247 EncodeWithoutBasicOffsetTable(of, 1, 15328);
248 CreateOneFrame(of, testedImageData, fragment_size, xsize, ysize, samplesPerPixel, 100);
251 if( !f->IsReadable() )
253 std::cerr << "-------------------------------\n"
254 << "Error while creating the file\n"
255 << "This file is considered to be not readable\n";
259 std::streambuf* sb = of->rdbuf();
267 // Step 1 : Create the header of the image
269 gdcm::File *fileToBuild = new gdcm::File();
270 std::ostringstream str;
272 // Set the image size
275 fileToBuild->InsertEntryString(str.str(),0x0028,0x0011); // Columns
278 fileToBuild->InsertEntryString(str.str(),0x0028,0x0010); // Rows
284 // fileToBuild->InsertEntryString(str.str(),0x0028,0x0008); // Number of Frames
287 // Set the pixel type
289 str << 8; //img.componentSize;
290 fileToBuild->InsertEntryString(str.str(),0x0028,0x0100); // Bits Allocated
293 str << 8; //img.componentUse;
294 fileToBuild->InsertEntryString(str.str(),0x0028,0x0101); // Bits Stored
297 str << 7; //( img.componentSize - 1 );
298 fileToBuild->InsertEntryString(str.str(),0x0028,0x0102); // High Bit
300 // Set the pixel representation
302 str << 0; //img.sign;
303 fileToBuild->InsertEntryString(str.str(),0x0028,0x0103); // Pixel Representation
305 // Set the samples per pixel
307 str << samplesPerPixel; //img.components;
308 fileToBuild->InsertEntryString(str.str(),0x0028,0x0002); // Samples per Pixel
310 // Step 2 : Create the output image
311 // std::cout << "2...";
312 // if( img.componentSize%8 > 0 )
314 // img.componentSize += 8-img.componentSize%8;
316 size_t size = xsize * ysize * 1 /*Z*/
317 * samplesPerPixel /* * img.componentSize / 8*/;
319 uint8_t *imageData = new uint8_t[size];
320 gdcm::FileHelper *fileH = new gdcm::FileHelper(fileToBuild);
321 //fileH->SetImageData(imageData,size);
322 assert( size == testedDataSize );
323 size = of->str().size();
324 //size = sb->in_avail();
325 std::cerr << "Size JPEG:" << size << std::endl;
326 //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
327 memcpy(imageData, of->str().c_str(), size);
328 fileH->SetImageData(imageData, size);
329 //str::string *s = of->str();
330 //fileH->SetWriteTypeToDcmExplVR();
331 fileH->SetWriteTypeToJPEG( );
332 std::string fileName = "/tmp/bla.dcm";
333 if( !fileH->Write(fileName) )
335 std::cerr << "Badddd" << std::endl;
338 std::ofstream out("/tmp/jpeg2.jpg");
339 //out.write( of->str(), of
340 //out << of->str(); //rdbuf is faster than going through str()
341 out.write( (char*)imageData, size);
342 //std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] <<
343 // imageData[8] << imageData[9] << std::endl;