1 /*=========================================================================
4 Module: $RCSfile: WriteDicomAsJPEG.cxx,v $
6 Date: $Date: 2005/10/18 19:54:25 $
7 Version: $Revision: 1.3 $
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"
27 #include "gdcmjpeg/8/jconfig.h"
28 #include "gdcmjpeg/8/jpeglib.h"
29 #include "gdcmjpeg/8/jinclude.h"
30 #include "gdcmjpeg/8/jerror.h"
33 #include "gdcmJPEGFragment.h"
37 #include "jdatasrc.cxx"
38 #include "jdatadst.cxx"
40 bool CreateOneFrame (std::ostream *fp, void *input_buffer, int fragment_size,
41 int image_width, int image_height, int sample_pixel, int quality)
43 JSAMPLE *image_buffer = (JSAMPLE*) input_buffer;
45 /* This struct contains the JPEG compression parameters and pointers to
46 * working space (which is allocated as needed by the JPEG library).
47 * It is possible to have several such structures, representing multiple
48 * compression/decompression processes, in existence at once. We refer
49 * to any one struct (and its associated working data) as a "JPEG object".
51 struct jpeg_compress_struct cinfo;
52 /* This struct represents a JPEG error handler. It is declared separately
53 * because applications often want to supply a specialized error handler
54 * (see the second half of this file for an example). But here we just
55 * take the easy way out and use the standard error handler, which will
56 * print a message on stderr and call exit() if compression fails.
57 * Note that this struct must live as long as the main JPEG parameter
58 * struct, to avoid dangling-pointer problems.
60 struct jpeg_error_mgr jerr;
62 //FILE* outfile; /* target FILE* /
63 JSAMPROW row_pointer[1]; /* pointer to JSAMPLE row[s] */
64 int row_stride; /* physical row width in image buffer */
66 /* Step 1: allocate and initialize JPEG compression object */
68 /* We have to set up the error handler first, in case the initialization
69 * step fails. (Unlikely, but it could happen if you are out of memory.)
70 * This routine fills in the contents of struct jerr, and returns jerr's
71 * address which we place into the link field in cinfo.
73 cinfo.err = jpeg_std_error(&jerr);
74 /* Now we can initialize the JPEG compression object. */
75 jpeg_create_compress(&cinfo);
77 /* Step 2: specify data destination (eg, a file) */
78 /* Note: steps 2 and 3 can be done in either order. */
80 /* Here we use the library-supplied code to send compressed data to a
81 * stdio stream. You can also write your own code to do something else.
82 * VERY IMPORTANT: use "b" option to fopen() if you are on a machine that
83 * requires it in order to write binary files.
85 // if ((outfile = fopen(filename, "wb")) == NULL) {
86 // fprintf(stderr, "can't open %s\n", filename);
90 jpeg_stdio_dest(&cinfo, fp, fragment_size);
92 /* Step 3: set parameters for compression */
94 /* First we supply a description of the input image.
95 * Four fields of the cinfo struct must be filled in:
97 cinfo.image_width = image_width;/* image width and height, in pixels */
98 cinfo.image_height = image_height;
99 if ( sample_pixel == 3 )
101 cinfo.input_components = 3; /* # of color components per pixel */
102 cinfo.in_color_space = JCS_RGB; /* colorspace of input image */
106 cinfo.input_components = 1; /* # of color components per pixel */
107 cinfo.in_color_space = JCS_GRAYSCALE; /* colorspace of input image */
109 /* Now use the library's routine to set default compression parameters.
110 * (You must set at least cinfo.in_color_space before calling this,
111 * since the defaults depend on the source color space.)
113 jpeg_set_defaults(&cinfo);
114 /* Now you can set any non-default parameters you wish to.
115 * Here we just illustrate the use of quality (quantization table) scaling:
117 jpeg_set_quality(&cinfo, quality, TRUE /* limit to baseline-JPEG values */);
119 /* Step 4: Start compressor */
121 /* TRUE ensures that we will write a complete interchange-JPEG file.
122 * Pass TRUE unless you are very sure of what you're doing.
124 jpeg_start_compress(&cinfo, TRUE);
126 /* Step 5: while (scan lines remain to be written) */
127 /* jpeg_write_scanlines(...); */
129 /* Here we use the library's state variable cinfo.next_scanline as the
130 * loop counter, so that we don't have to keep track ourselves.
131 * To keep things simple, we pass one scanline per call; you can pass
132 * more if you wish, though.
134 if (sample_pixel == 3)
136 row_stride = image_width * 3;/* JSAMPLEs per row in image_buffer */
140 row_stride = image_width * 1;/* JSAMPLEs per row in image_buffer */
144 while (cinfo.next_scanline < cinfo.image_height) {
145 /* jpeg_write_scanlines expects an array of pointers to scanlines.
146 * Here the array is only one element long, but you could pass
147 * more than one scanline at a time if that's more convenient.
149 row_pointer[0] = & image_buffer[cinfo.next_scanline * row_stride];
151 (void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
154 /* Step 6: Finish compression */
156 jpeg_finish_compress(&cinfo);
158 /* After finish_compress, we can close the output file. */
160 // fclose(fp); --> the caller will close (multiframe treatement)
162 /* Step 7: release JPEG compression object */
164 /* This is an important step since it will release a good deal of memory. */
165 jpeg_destroy_compress(&cinfo);
167 /* And we're done! */
172 // Open a dicom file and compress it as JPEG stream
173 int main(int argc, char *argv[])
178 std::string filename = argv[1];
180 // Step 1 : Create the header of the image
181 gdcm::File *f = new gdcm::File();
182 f->SetLoadMode ( gdcm::LD_ALL ); // Load everything
183 f->SetFileName( filename );
186 gdcm::FileHelper *tested = new gdcm::FileHelper( f );
187 std::string PixelType = tested->GetFile()->GetPixelType();
188 int xsize = f->GetXSize();
189 int ysize = f->GetYSize();
191 int samplesPerPixel = f->GetSamplesPerPixel();
192 size_t testedDataSize = tested->GetImageDataSize();
193 std::cerr << "testedDataSize:" << testedDataSize << std::endl;
194 uint8_t *testedImageData = tested->GetImageData();
196 //std::ofstream *of = new std::ofstream("/tmp/jpeg.jpg");
197 std::ostringstream *of = new std::ostringstream();
198 std::cout << "X: " << xsize << std::endl;
199 std::cout << "Y: " << ysize << std::endl;
200 std::cout << "Sample: " << samplesPerPixel << std::endl;
201 int fragment_size = xsize*ysize*samplesPerPixel;
202 CreateOneFrame(of, testedImageData, fragment_size, xsize, ysize, samplesPerPixel, 100);
203 if( !f->IsReadable() )
205 std::cerr << "-------------------------------\n"
206 << "Error while creating the file\n"
207 << "This file is considered to be not readable\n";
211 std::streambuf* sb = of->rdbuf();
219 // Step 1 : Create the header of the image
221 gdcm::File *fileToBuild = new gdcm::File();
222 std::ostringstream str;
224 // Set the image size
227 fileToBuild->InsertEntryString(str.str(),0x0028,0x0011); // Columns
230 fileToBuild->InsertEntryString(str.str(),0x0028,0x0010); // Rows
236 // fileToBuild->InsertEntryString(str.str(),0x0028,0x0008); // Number of Frames
239 // Set the pixel type
241 str << 8; //img.componentSize;
242 fileToBuild->InsertEntryString(str.str(),0x0028,0x0100); // Bits Allocated
245 str << 8; //img.componentUse;
246 fileToBuild->InsertEntryString(str.str(),0x0028,0x0101); // Bits Stored
249 str << 7; //( img.componentSize - 1 );
250 fileToBuild->InsertEntryString(str.str(),0x0028,0x0102); // High Bit
252 // Set the pixel representation
254 str << 0; //img.sign;
255 fileToBuild->InsertEntryString(str.str(),0x0028,0x0103); // Pixel Representation
257 // Set the samples per pixel
259 str << samplesPerPixel; //img.components;
260 fileToBuild->InsertEntryString(str.str(),0x0028,0x0002); // Samples per Pixel
262 // Step 2 : Create the output image
263 // std::cout << "2...";
264 // if( img.componentSize%8 > 0 )
266 // img.componentSize += 8-img.componentSize%8;
268 size_t size = xsize * ysize * 1 /*Z*/
269 * samplesPerPixel /* * img.componentSize / 8*/;
271 uint8_t *imageData = new uint8_t[size];
272 gdcm::FileHelper *fileH = new gdcm::FileHelper(fileToBuild);
273 //fileH->SetImageData(imageData,size);
274 assert( size == testedDataSize );
275 size = of->str().size();
276 //size = sb->in_avail();
277 std::cerr << "Size JPEG:" << size << std::endl;
278 //fileH->SetImageData((uint8_t*)of->str().c_str(), size);
279 memcpy(imageData, of->str().c_str(), size);
280 fileH->SetImageData(imageData, size);
281 //str::string *s = of->str();
282 //fileH->SetWriteTypeToDcmExplVR();
283 fileH->SetWriteTypeToJPEG( );
284 std::string fileName = "/tmp/bla.dcm";
285 if( !fileH->Write(fileName) )
287 std::cerr << "Badddd" << std::endl;
290 std::ofstream out("/tmp/jpeg2.jpg");
291 //out.write( of->str(), of
292 //out << of->str(); //rdbuf is faster than going through str()
293 out.write( (char*)imageData, size);
294 std::cerr << "JPEG marker is: " << imageData[6] << imageData[7] <<
295 imageData[8] << imageData[9] << std::endl;