]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
doxygenation
[gdcm.git] / src / gdcmFile.cxx
1 // gdcmFile.cxx
2 //-----------------------------------------------------------------------------
3 #include "gdcmFile.h"
4 #include "gdcmDebug.h"
5 #include "jpeg/ljpg/jpegless.h"
6
7 typedef std::pair<TagHeaderEntryHT::iterator,TagHeaderEntryHT::iterator> IterHT;
8
9 //-----------------------------------------------------------------------------
10 // Constructor / Destructor
11 /**
12  * \ingroup   gdcmFile
13  * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
14  *        file (see SetFileName, SetDcmTag and Write)
15  *        Opens (in read only and when possible) an existing file and checks
16  *        for DICOM compliance. Returns NULL on failure.
17  * \note  the in-memory representation of all available tags found in
18  *        the DICOM header is post-poned to first header information access.
19  *        This avoid a double parsing of public part of the header when
20  *        one sets an a posteriori shadow dictionary (efficiency can be
21  *        seen as a side effect).   
22  * @param header file to be opened for reading datas
23  * @return      
24  */
25 gdcmFile::gdcmFile(gdcmHeader *header) {
26    Header=header;
27    SelfHeader=false;
28    PixelRead=-1; // no ImageData read yet.
29
30    if (Header->IsReadable())
31       SetPixelDataSizeFromHeader();
32 }
33
34 /**
35  * \ingroup   gdcmFile
36  * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
37  *        file (see SetFileName, SetDcmTag and Write)
38  *        Opens (in read only and when possible) an existing file and checks
39  *        for DICOM compliance. Returns NULL on failure.
40  * \note  the in-memory representation of all available tags found in
41  *        the DICOM header is post-poned to first header information access.
42  *        This avoid a double parsing of public part of the header when
43  *        one sets an a posteriori shadow dictionary (efficiency can be
44  *        seen as a side effect).   
45  * @param filename file to be opened for parsing
46  * @param   exception_on_error whether we throw an exception or not
47  * @param   enable_sequences = true to allow the header 
48  *          to be parsed *inside* the SeQuences, 
49  *          when they have an actual length 
50  * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
51  * @param   ignore_shadow to allow skipping the shadow elements, 
52  *          to save memory space.
53  * \warning The TRUE value for this param has to be used 
54  *          with a FALSE value for the 'enable_sequence' param.
55  *          ('public elements' may be embedded in 'shadow Sequences')
56  */
57 gdcmFile::gdcmFile(std::string & filename, 
58                    bool exception_on_error,
59                    bool enable_sequences, 
60                    bool ignore_shadow) {
61    Header=new gdcmHeader(filename.c_str(),
62                          exception_on_error,
63                          enable_sequences,
64                          ignore_shadow);
65    SelfHeader=true;
66    PixelRead=-1; // no ImageData read yet.
67
68    if (Header->IsReadable())
69       SetPixelDataSizeFromHeader();
70 }
71
72 /**
73  * \ingroup   gdcmFile
74  * \brief Constructor dedicated to writing a new DICOMV3 part10 compliant
75  *        file (see SetFileName, SetDcmTag and Write)
76  *        Opens (in read only and when possible) an existing file and checks
77  *        for DICOM compliance. Returns NULL on failure.
78  * \note  the in-memory representation of all available tags found in
79  *        the DICOM header is post-poned to first header information access.
80  *        This avoid a double parsing of public part of the header when
81  *        one sets an a posteriori shadow dictionary (efficiency can be
82  *        seen as a side effect).   
83  * @param filename file to be opened for parsing
84  * @param   exception_on_error whether we throw an exception or not
85  * @param   enable_sequences = true to allow the header 
86  *          to be parsed *inside* the SeQuences, 
87  *          when they have an actual length 
88  * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
89  * @param   ignore_shadow to allow skipping the shadow elements, 
90  *          to save memory space.
91  * \warning The TRUE value for this param has to be used 
92  *          with a FALSE value for the 'enable_sequence' param.
93  *          ('public elements' may be embedded in 'shadow Sequences')
94  */
95  gdcmFile::gdcmFile(const char * filename, 
96                    bool exception_on_error,
97                    bool enable_sequences, 
98                    bool ignore_shadow) {
99    Header=new gdcmHeader(filename,
100                          exception_on_error,
101                          enable_sequences,
102                          ignore_shadow);
103    SelfHeader=true;
104    PixelRead=-1; // no ImageData read yet.
105
106    if (Header->IsReadable())
107       SetPixelDataSizeFromHeader();
108 }
109
110 /**
111  * \ingroup   gdcmFile
112  * \brief canonical destructor
113  * \note  If the gdcmHeader is created by the gdcmFile, it is destroyed
114  *        by the gdcmFile
115  */
116 gdcmFile::~gdcmFile(void) {
117    if(SelfHeader)
118       delete Header;
119    Header=NULL;
120 }
121
122 //-----------------------------------------------------------------------------
123 // Print
124
125 //-----------------------------------------------------------------------------
126 // Public
127 /**
128  * \ingroup   gdcmFile
129  * \brief returns the gdcmHeader *Header   
130  * @return      
131  */
132 gdcmHeader *gdcmFile::GetHeader(void) {
133    return(Header);
134 }
135
136 /**
137  * \ingroup   gdcmFile
138  * \brief     computes the length (in bytes) to ALLOCATE to receive the
139  *            image(s) pixels (multiframes taken into account)          
140  * \warning : it is NOT the group 7FE0 length
141  *          (no interest for compressed images).
142  * @return length to allocate
143  */
144 void gdcmFile::SetPixelDataSizeFromHeader(void) {
145    // see PS 3.3-2003 : C.7.6.3.2.1  
146    // 
147    //   MONOCHROME1
148    //   MONOCHROME2
149    //   PALETTE COLOR
150    //   RGB
151    //   HSV  (Retired)
152    //   ARGB (Retired)
153    //   CMYK (Retired)
154    //   YBR_FULL
155    //   YBR_FULL_422 (no LUT, no Palette)
156    //   YBR_PARTIAL_422
157    //   YBR_ICT
158    //   YBR_RCT
159
160    // LUT's
161    // ex : gdcm-US-ALOKA-16.dcm
162    // 0028|1221 [OW]   [Segmented Red Palette Color Lookup Table Data]
163    // 0028|1222 [OW]   [Segmented Green Palette Color Lookup Table Data]  
164    // 0028|1223 [OW]   [Segmented Blue Palette Color Lookup Table Data]
165
166    // ex  : OT-PAL-8-face.dcm
167    // 0028|1201 [US]   [Red Palette Color Lookup Table Data]
168    // 0028|1202 [US]   [Green Palette Color Lookup Table Data]
169    // 0028|1203 [US]   [Blue Palette Color Lookup Table Data]
170
171    int nb;
172    std::string str_nb;
173    str_nb=Header->GetEntryByNumber(0x0028,0x0100);
174    if (str_nb == GDCM_UNFOUND ) {
175       nb = 16;
176    } else {
177       nb = atoi(str_nb.c_str() );
178       if (nb == 12) nb =16;
179    }
180    lgrTotale =  lgrTotaleRaw = Header->GetXSize() * Header->GetYSize() 
181               * Header->GetZSize() * (nb/8)* Header->GetSamplesPerPixel();
182    std::string str_PhotometricInterpretation = 
183                              Header->GetEntryByNumber(0x0028,0x0004);
184                              
185    /*if ( str_PhotometricInterpretation == "PALETTE COLOR " )*/
186    // pb when undealt Segmented Palette Color
187    
188     if (Header->HasLUT()) { 
189       lgrTotale*=3;
190    }
191 }
192
193 /**
194  * \ingroup   gdcmFile
195  * \brief     Returns the size (in bytes) of required memory to hold
196  *            the pixel data represented in this file.
197  * @return    The size of pixel data in bytes.
198  */
199 size_t gdcmFile::GetImageDataSize(void) {
200    return (lgrTotale);
201 }
202
203 /**
204  * \ingroup   gdcmFile
205  * \brief     Returns the size (in bytes) of required memory to hold
206  *            the pixel data represented in this file, when user DOESN'T want 
207  *            to get RGB pixels image when it's stored as a PALETTE COLOR image
208  *            -the (vtk) user is supposed to know how deal with LUTs- 
209  * \warning   to be used with GetImagePixelsRaw()
210  * @return    The size of pixel data in bytes.
211  */
212 size_t gdcmFile::GetImageDataSizeRaw(void) {
213    return (lgrTotaleRaw);
214 }
215
216 /**
217  * \ingroup gdcmFile
218  * \brief   Allocates necessary memory, copies the pixel data
219  *          (image[s]/volume[s]) to newly allocated zone.
220  *          Transforms YBR pixels into RGB pixels if any
221  *          Transforms 3 planes R, G, B into a single RGB Plane
222  *          Transforms single Grey plane + 3 Palettes into a RGB Plane
223  * @return  Pointer to newly allocated pixel data.
224  *          NULL if alloc fails 
225  */
226 void * gdcmFile::GetImageData (void) {
227    PixelData = (void *) malloc(lgrTotale);
228    if (PixelData)
229       GetImageDataIntoVector(PixelData, lgrTotale);
230       
231    PixelRead=0; // no PixelRaw
232    return(PixelData);
233 }
234
235 /**
236  * \ingroup gdcmFile
237  * \brief   Copies at most MaxSize bytes of pixel data to caller's
238  *          memory space.
239  * \warning This function was designed to avoid people that want to build
240  *          a volume from an image stack to need first to get the image pixels 
241  *          and then move them to the volume area.
242  *          It's absolutely useless for any VTK user since vtk chooses 
243  *          to invert the lines of an image, that is the last line comes first
244  *          (for some axis related reasons?). Hence he will have 
245  *          to load the image line by line, starting from the end.
246  *          VTK users have to call GetImageData
247  *     
248  * @param   destination Address (in caller's memory space) at which the
249  *          pixel data should be copied
250  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
251  *          is not sufficient to hold the pixel data the copy is not
252  *          executed (i.e. no partial copy).
253  * @return  On success, the number of bytes actually copied. Zero on
254  *          failure e.g. MaxSize is lower than necessary.
255  */
256 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
257    size_t l = GetImageDataIntoVectorRaw (destination, MaxSize);
258    PixelRead=0 ; // no PixelRaw
259    if (!Header->HasLUT())
260       return lgrTotale; 
261                             
262    // from Lut R + Lut G + Lut B
263    unsigned char * newDest = (unsigned char *)malloc(lgrTotale);
264    unsigned char * a       = (unsigned char *)destination;       
265    unsigned char * lutRGBA =                  Header->GetLUTRGBA();
266    if (lutRGBA) {           
267       int l = lgrTotaleRaw;
268       memmove(newDest, destination, l);// move Gray pixels to temp area     
269       int j;     
270       for (int i=0;i<l; i++) {         // Build RGB Pixels
271          j=newDest[i]*4;
272          *a++ = lutRGBA[j]; 
273          *a++ = lutRGBA[j+1];
274          *a++ = lutRGBA[j+2];
275       }
276       free(newDest);
277     
278    // now, it's an RGB image
279    // Lets's write it in the Header
280
281          // CreateOrReplaceIfExist ?
282          
283    std::string spp = "3";        // Samples Per Pixel
284    Header->SetEntryByNumber(spp,0x0028,0x0002);
285    std::string rgb= "RGB ";      // Photometric Interpretation
286    Header->SetEntryByNumber(rgb,0x0028,0x0004);
287    std::string planConfig = "0"; // Planar Configuration
288    Header->SetEntryByNumber(planConfig,0x0028,0x0006);
289
290    } else { 
291              // need to make RGB Pixels (?)
292              //    from grey Pixels (?!)
293              //     and Gray Lut  (!?!) 
294              //    or Segmented xxx Palette Color Lookup Table Data and so on
295                                                   
296          // Oops! I get one (gdcm-US-ALOKA-16.dcm)
297          // No idea how to manage such an image 
298          // It seems that *no Dicom Viewer* has any idea :-(
299          // Segmented xxx Palette Color are *more* than 65535 long ?!?
300                    
301       std::string rgb= "MONOCHROME1 ";      // Photometric Interpretation
302       Header->SetEntryByNumber(rgb,0x0028,0x0004);                                 
303    }             
304    // TODO : Drop Palette Color out of the Header?           
305    return lgrTotale; 
306 }
307
308 /**
309  * \ingroup gdcmFile
310  * \brief   Allocates necessary memory, copies the pixel data
311  *          (image[s]/volume[s]) to newly allocated zone.
312  *          Transforms YBR pixels into RGB pixels if any
313  *          Transforms 3 planes R, G, B into a single RGB Plane
314  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
315  * @return  Pointer to newly allocated pixel data.
316  * \        NULL if alloc fails 
317  */
318 void * gdcmFile::GetImageDataRaw (void) {
319    if (Header->HasLUT())
320       lgrTotale /= 3;  // TODO Let gdcmHeadar user a chance 
321                        // to get the right value
322                        // Create a member lgrTotaleRaw ???
323    PixelData = (void *) malloc(lgrTotale);
324    if (PixelData)
325       GetImageDataIntoVectorRaw(PixelData, lgrTotale);
326    PixelRead=1; // PixelRaw
327    return(PixelData);
328 }
329
330 /**
331  * \ingroup gdcmFile
332  * \brief   Copies at most MaxSize bytes of pixel data to caller's
333  *          memory space.
334  * \warning This function was designed to avoid people that want to build
335  *          a volume from an image stack to need first to get the image pixels 
336  *          and then move them to the volume area.
337  *          It's absolutely useless for any VTK user since vtk chooses 
338  *          to invert the lines of an image, that is the last line comes first
339  *          (for some axis related reasons?). Hence he will have 
340  *          to load the image line by line, starting from the end.
341  *          VTK users hace to call GetImageData
342  * \warning DOES NOT transform the Grey Plane + Palette Color (if any) 
343  *                   into a single RGB Pixels Plane
344  *          the (VTK) user will manage the palettes
345  *     
346  * @param   destination Address (in caller's memory space) at which the
347  *          pixel data should be copied
348  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
349  *          is not sufficient to hold the pixel data the copy is not
350  *          executed (i.e. no partial copy).
351  * @return  On success, the number of bytes actually copied. Zero on
352  *          failure e.g. MaxSize is lower than necessary.
353  */
354 size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t MaxSize) {
355
356    int nb, nbu, highBit, signe;
357    std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
358    PixelRead=1 ; // PixelRaw
359  
360    if ( lgrTotale > MaxSize ) {
361       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
362                      "than caller's expected MaxSize");
363       return (size_t)0; 
364    }
365         
366    (void)ReadPixelData(destination);
367         
368         // Number of Bits Allocated for storing a Pixel
369    str_nb = Header->GetEntryByNumber(0x0028,0x0100);
370    if (str_nb == GDCM_UNFOUND ) {
371       nb = 16;
372    } else {
373       nb = atoi(str_nb.c_str() );
374    }    
375         // Number of Bits actually used
376    str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
377    if (str_nbu == GDCM_UNFOUND ) {
378       nbu = nb;
379    } else {
380       nbu = atoi(str_nbu.c_str() );
381    }            
382         // High Bit Position
383    str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
384    if (str_highBit == GDCM_UNFOUND ) {
385       highBit = nb - 1;
386    } else {
387       highBit = atoi(str_highBit.c_str() );
388    }            
389         // Pixel sign
390         // 0 = Unsigned
391         // 1 = Signed
392    str_signe=Header->GetEntryByNumber(0x0028,0x0103);
393    if (str_signe == GDCM_UNFOUND ) {
394       signe = 0;  // default is unsigned
395    } else {
396       signe = atoi(str_signe.c_str() );
397    }
398
399    // re arange bytes inside the integer (processor endianity)
400    if (nb != 8)
401      SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
402      
403    // to avoid pb with some xmedcon breakers images 
404    if (nb==16 && nbu<nb && signe==0) {
405      int l = (int)lgrTotale / (nb/8);
406      guint16 *deb = (guint16 *)destination;
407      for(int i = 0; i<l; i++) {
408         if(*deb == 0xffff) 
409            *deb=0; 
410            deb++;   
411          }
412     }
413    // re arange bits inside the bytes
414    if (nbu != nb){
415       int l = (int)lgrTotale / (nb/8);
416       if (nb == 16) {
417          guint16 mask = 0xffff;
418          mask = mask >> (nb-nbu);
419          guint16 *deb = (guint16 *)destination;
420          for(int i = 0; i<l; i++) {
421             *deb = (*deb >> (nbu-highBit-1)) & mask;
422             deb ++;
423          }
424       } else if (nb == 32 ) {
425          guint32 mask = 0xffffffff;
426          mask = mask >> (nb-nbu);
427          guint32 *deb = (guint32 *)destination;
428          for(int i = 0; i<l; i++) {
429             *deb = (*deb >> (nbu-highBit-1)) & mask;
430             deb ++;
431          }
432       } else {
433          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
434          return (size_t)0; 
435       }
436    } 
437 // DO NOT remove this commented out code .
438 // Nobody knows what's expecting you ...
439 // Just to 'see' what was actually read on disk :-(
440
441 //   FILE * f2;
442 //   f2 = fopen("SpuriousFile.RAW","wb");
443 //   fwrite(destination,lgrTotale,1,f2);
444 //   fclose(f2);
445
446    // Deal with the color
447    // -------------------
448    
449        std::string str_PhotometricInterpretation = 
450                  Header->GetEntryByNumber(0x0028,0x0004);
451                    
452       if ( (str_PhotometricInterpretation == "MONOCHROME1 ") 
453         || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
454          return lgrTotale; 
455       }
456       
457    // Planar configuration = 0 : Pixels are already RGB
458    // Planar configuration = 1 : 3 planes : R, G, B
459    // Planar configuration = 2 : 1 gray Plane + 3 LUT
460
461    // Well ... supposed to be !
462    // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
463    //                            PhotometricInterpretation=PALETTE COLOR
464    // and heuristic has to be found :-( 
465
466       int planConf=Header->GetPlanarConfiguration();  // 0028,0006
467
468       // Whatever Planar Configuration is, 
469       // "PALETTE COLOR " implies that we deal with the palette. 
470       if (str_PhotometricInterpretation == "PALETTE COLOR ")
471          planConf=2;
472
473       switch (planConf) {
474       case 0:                              
475          //       Pixels are already RGB
476          break;
477     
478       case 1:
479
480          {
481          if (str_PhotometricInterpretation == "YBR_FULL") { 
482          
483    // Warning : YBR_FULL_422 acts as RGB
484    //         : we need to make RGB Pixels from Planes Y,cB,cR
485          
486          // to see the tricks about YBR_FULL, YBR_FULL_422, 
487          // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
488          //   ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
489          // and be *very* affraid
490          //
491             int l = Header->GetXSize()*Header->GetYSize();
492             int nbFrames = Header->GetZSize();
493
494             unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
495             unsigned char *x  = newDest;
496             unsigned char * a = (unsigned char *)destination;
497             unsigned char * b = a + l;
498             unsigned char * c = b + l;
499             double R,G,B;
500
501             // TODO : Replace by the 'well known' 
502             //        integer computation counterpart
503             // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
504             // for code optimisation
505             
506             for (int i=0;i<nbFrames;i++) {
507                for (int j=0;j<l; j++) {
508                   R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
509                   G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
510                   B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
511
512                   if (R<0.0)   R=0.0;
513                   if (G<0.0)   G=0.0;
514                   if (B<0.0)   B=0.0;
515                   if (R>255.0) R=255.0;
516                   if (G>255.0) G=255.0;
517                   if (B>255.0) B=255.0;
518
519                   *(x++) = (unsigned char)R;
520                   *(x++) = (unsigned char)G;
521                   *(x++) = (unsigned char)B;
522                   a++; b++; c++;  
523                }
524            }
525             memmove(destination,newDest,lgrTotale);
526             free(newDest);
527
528         } else {
529          
530          //       need to make RGB Pixels from R,G,B Planes
531          //       (all the Frames at a time)
532
533             int l = Header->GetXSize()*Header->GetYSize()*Header->GetZSize();
534
535             char * newDest = (char*) malloc(lgrTotale);
536             char * x = newDest;
537             char * a = (char *)destination;
538             char * b = a + l;
539             char * c = b + l;
540
541             for (int j=0;j<l; j++) {
542                *(x++) = *(a++);
543                *(x++) = *(b++);
544                *(x++) = *(c++);  
545             }           
546             memmove(destination,newDest,lgrTotale);
547             free(newDest);
548         }         
549          break;
550        }     
551        case 2:                      
552          //       Palettes were found
553          //       Let the user deal with them !
554          return lgrTotale;        
555    } 
556    // now, it's an RGB image
557    // Lets's write it in the Header
558
559    // CreateOrReplaceIfExist ?
560
561    std::string spp = "3";        // Samples Per Pixel
562    Header->SetEntryByNumber(spp,0x0028,0x0002);
563    std::string rgb="RGB ";   // Photometric Interpretation
564    Header->SetEntryByNumber(rgb,0x0028,0x0004);
565
566    std::string planConfig = "0"; // Planar Configuration
567    Header->SetEntryByNumber(planConfig,0x0028,0x0006);
568          
569          // TODO : Drop Palette Color out of the Header? 
570    return lgrTotale; 
571 }
572
573 /**
574  * \ingroup   gdcmFile
575  * \brief performs a shadow copy (not a deep copy) of the user given
576  *        pixel area.
577  *        'image' Pixels are presented as C-like 2D arrays : line per line.
578  *        'volume'Pixels are presented as C-like 3D arrays : lane per plane 
579  * \warning user is kindly requested NOT TO 'free' the Pixel area
580  * @param inData user supplied pixel area
581  * @param ExpectedSize total image size, in Bytes
582  *
583  * @return boolean      
584  */
585 bool gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
586    Header->SetImageDataSize(ExpectedSize);
587    PixelData = inData;
588    lgrTotale = ExpectedSize;
589    return(true);
590 }
591
592 /**
593  * \ingroup   gdcmFile
594  * \brief Writes on disk A SINGLE Dicom file
595  *        NO test is performed on  processor "Endiannity".
596  *        It's up to the user to call his Reader properly
597  * @param fileName name of the file to be created
598  *                 (any already existing file is over written)
599  * @return false if write fails 
600  */
601
602 bool gdcmFile::WriteRawData (std::string fileName) {
603    FILE * fp1;
604    fp1 = fopen(fileName.c_str(),"wb");
605    if (fp1 == NULL) {
606       printf("Fail to open (write) file [%s] \n",fileName.c_str());
607       return (false);
608    }    
609    fwrite (PixelData,lgrTotale, 1, fp1);
610    fclose (fp1);
611    return(true);
612 }
613
614 /**
615  * \ingroup   gdcmFile
616  * \brief Writes on disk A SINGLE Dicom file, 
617  *        using the Implicit Value Representation convention
618  *        NO test is performed on  processor "Endiannity".
619  * @param fileName name of the file to be created
620  *                 (any already existing file is overwritten)
621  * @return false if write fails 
622  */
623
624 bool gdcmFile::WriteDcmImplVR (std::string fileName) {
625    return WriteBase(fileName, ImplicitVR);
626 }
627
628 /**
629  * \ingroup   gdcmFile
630  * \brief Writes on disk A SINGLE Dicom file, 
631  *        using the Implicit Value Representation convention
632  *        NO test is performed on  processor "Endiannity". * @param fileName name of the file to be created
633  *                 (any already existing file is overwritten)
634  * @return false if write fails 
635  */
636  
637 bool gdcmFile::WriteDcmImplVR (const char* fileName) {
638    return WriteDcmImplVR (std::string (fileName));
639 }
640         
641 /**
642  * \ingroup   gdcmFile
643 * \brief Writes on disk A SINGLE Dicom file, 
644  *        using the Explicit Value Representation convention
645  *        NO test is performed on  processor "Endiannity". * @param fileName name of the file to be created
646  *                 (any already existing file is overwritten)
647  * @return false if write fails 
648  */
649
650 bool gdcmFile::WriteDcmExplVR (std::string fileName) {
651    return WriteBase(fileName, ExplicitVR);
652 }
653         
654 /**
655  * \ingroup   gdcmFile
656  * \brief Writes on disk A SINGLE Dicom file, 
657  *        using the ACR-NEMA convention
658  *        NO test is performed on  processor "Endiannity".
659  *        (a l'attention des logiciels cliniques 
660  *        qui ne prennent en entrée QUE des images ACR ...
661  * \warning if a DICOM_V3 header is supplied,
662  *         groups < 0x0008 and shadow groups are ignored
663  * \warning NO TEST is performed on processor "Endiannity".
664  * @param fileName name of the file to be created
665  *                 (any already existing file is overwritten)
666  * @return false if write fails         
667  */
668
669 bool gdcmFile::WriteAcr (std::string fileName) {
670    return WriteBase(fileName, ACR);
671 }
672
673 //-----------------------------------------------------------------------------
674 // Protected
675 /**
676  * \ingroup   gdcmFile
677  * \brief NOT a end user inteded function
678  *        (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
679  * @param fileName name of the file to be created
680  *                 (any already existing file is overwritten)
681  * @param  type file type (ExplicitVR, ImplicitVR, ...)
682  * @return false if write fails         
683  */
684 bool gdcmFile::WriteBase (std::string fileName, FileType type) {
685
686    FILE * fp1;
687    
688    if (PixelRead==-1 && type != ExplicitVR) {
689       return false;                
690    }
691
692    fp1 = fopen(fileName.c_str(),"wb");
693    if (fp1 == NULL) {
694       printf("Failed to open (write) File [%s] \n",fileName.c_str());
695       return (false);
696    }
697
698    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
699       char * filePreamble;
700       // writing Dicom File Preamble
701       filePreamble=(char*)calloc(128,1);
702       fwrite(filePreamble,128,1,fp1);
703       fwrite("DICM",4,1,fp1);
704       free (filePreamble);
705    }
706
707    // --------------------------------------------------------------
708    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
709    //
710    // if recognition code tells us we dealt with a LibIDO image
711    // we reproduce on disk the switch between lineNumber and columnNumber
712    // just before writting ...
713    
714    // TODO : the best trick would be *change* the recognition code
715    //        but pb expected if user deals with, e.g. COMPLEX images
716
717    std::string rows, columns; 
718    if ( Header->GetFileType() == ACR_LIBIDO){
719          rows    = Header->GetEntryByNumber(0x0028, 0x0010);
720          columns = Header->GetEntryByNumber(0x0028, 0x0011);
721          Header->SetEntryByNumber(columns,  0x0028, 0x0010);
722          Header->SetEntryByNumber(rows   ,  0x0028, 0x0011);
723    }    
724    // ----------------- End of Special Patch ----------------
725    
726    // TODO : get the grPixel, numPixel values (for some ACR-NEMA images only)
727    
728    guint16 grPixel =Header->GetGrPixel();
729    guint16 numPixel=Header->GetNumPixel();;
730     
731    // Update Pixel Data Length
732    // the *last* of the (GrPixel, NumPixel), if many.
733           
734    TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel); 
735    TagHeaderEntryHT::iterator p2;
736    gdcmHeaderEntry * PixelElement;
737    
738    IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym   
739
740    if (Header->GetEntry().count(key) == 1) // only the first is significant
741       p2=it.first; // iterator on the first (unique) synonym
742    else
743       p2=it.second;// iterator on the last synonym
744    
745    PixelElement=p2->second;        // H Table target column (2-nd col)
746   // PixelElement->SetPrintLevel(2);
747   // PixelElement->Print();      
748  
749    if (PixelRead==1)
750       PixelElement->SetLength(lgrTotaleRaw);
751    else if (PixelRead==0)
752       PixelElement->SetLength(lgrTotale);
753    
754    //PixelElement->SetPrintLevel(2);
755    //PixelElement->Print();    
756    Header->Write(fp1, type);
757
758    // --------------------------------------------------------------
759    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
760    // 
761    // ...and we restore the Header to be Dicom Compliant again 
762    // just after writting
763
764    if (Header->GetFileType() == ACR_LIBIDO){
765          Header->SetEntryByNumber(rows   , 0x0028, 0x0010);
766          Header->SetEntryByNumber(columns, 0x0028, 0x0011);
767    }    
768    // ----------------- End of Special Patch ----------------
769    
770    fwrite(PixelData, lgrTotale, 1, fp1);
771    fclose (fp1);
772    return(true);
773 }
774
775 //-----------------------------------------------------------------------------
776 // Private
777 /**
778  * \ingroup gdcmFile
779  * \brief   Swap the bytes, according to swap code.
780  * \warning not end user intended
781  * @param   im area to deal with
782  * @param   swap swap code
783  * @param   lgr Area Length
784  * @param   nb Pixels Bit number 
785  */
786 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
787 guint32 s32;
788 guint16 fort,faible;
789 int i;
790
791 if(nb == 16)  
792    switch(swap) {
793       case 0:
794       case 12:
795       case 1234:
796          break;
797                 
798       case 21:
799       case 3412:
800       case 2143:
801       case 4321:
802
803          for(i=0;i<lgr/2;i++) {
804             ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
805                                         | ((((unsigned short int*)im)[i])<<8);
806         }
807          break;
808                         
809       default:
810          printf("SWAP value (16 bits) not allowed : %d\n", swap);
811    } 
812  
813 if( nb == 32 )
814    switch (swap) {
815       case 0:
816       case 1234:
817          break;
818
819       case 4321:
820          for(i=0;i<lgr/4;i++) {
821             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
822             fort  =((unsigned long int*)im)[i]>>16;
823             fort=  (fort>>8)   | (fort<<8);
824             faible=(faible>>8) | (faible<<8);
825             s32=faible;
826             ((unsigned long int*)im)[i]=(s32<<16)|fort;
827          }
828          break;
829
830       case 2143:
831          for(i=0;i<lgr/4;i++) {
832             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
833             fort=((unsigned long int*)im)[i]>>16;
834             fort=  (fort>>8)   | (fort<<8);
835             faible=(faible>>8) | (faible<<8);
836             s32=fort; 
837             ((unsigned long int*)im)[i]=(s32<<16)|faible;
838          }
839          break;
840   
841       case 3412:
842          for(i=0;i<lgr/4;i++) {
843             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
844             fort=((unsigned long int*)im)[i]>>16;                  
845             s32=faible; 
846             ((unsigned long int*)im)[i]=(s32<<16)|fort;
847          }                 
848          break; 
849                                 
850       default:
851          printf("SWAP value (32 bits) not allowed : %d\n", swap);
852    } 
853 return;
854 }
855
856 /**
857  * \ingroup gdcmFile
858  * \brief   Read pixel data from disk (optionaly decompressing) into the
859  *          caller specified memory location.
860  * @param   destination where the pixel data should be stored.
861  *
862  */
863 bool gdcmFile::ReadPixelData(void* destination) {
864
865    FILE *fp;
866
867    if ( !(fp=Header->OpenFile()))
868       return false;
869    if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
870       Header->CloseFile();
871       return false;
872    }
873    // ----------------------  Compacted File (12 Bits Per Pixel)
874    /* unpack 12 Bits pixels into 16 Bits pixels */
875    /* 2 pixels 12bit =     [0xABCDEF]           */
876    /* 2 pixels 16bit = [0x0ABD] + [0x0FCE]      */
877    
878    if (Header->GetBitsAllocated()==12) {
879       int nbPixels = Header->GetXSize() * Header->GetYSize();
880       unsigned char b0, b1, b2;
881       
882       unsigned short int* pdestination = (unsigned short int*)destination;    
883       for(int p=0;p<nbPixels;p+=2) {
884          fread(&b0,1,1,fp);
885          fread(&b1,1,1,fp);
886          fread(&b2,1,1,fp);      
887          //Two steps is necessary to please VC++
888          *pdestination++ =  ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
889                               /* A */            /* B */             /* D */
890          *pdestination++ =  ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
891                              /* F */               /* C */           /* E */
892                   
893         // Troubles expected on Big-Endian processors ?       
894       }
895
896       Header->CloseFile();
897       return(true);
898    }        
899
900    // ----------------------  Uncompressed File
901    if ( !Header->IsDicomV3()                             ||
902         Header->IsImplicitVRLittleEndianTransferSyntax() ||
903         Header->IsExplicitVRLittleEndianTransferSyntax() ||
904         Header->IsExplicitVRBigEndianTransferSyntax()    ||
905         Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
906
907       size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
908       if ( ItemRead != 1 ) {
909          Header->CloseFile();
910          return false;
911       } else {
912          Header->CloseFile();
913          return true;
914       }
915    } 
916
917    // ---------------------- Run Length Encoding
918    if (Header->IsRLELossLessTransferSyntax()) {
919       bool res = (bool)gdcm_read_RLE_file (fp,destination);
920       Header->CloseFile();
921       return res; 
922    }  
923     
924    // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000 
925    int nb;
926    std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
927    if (str_nb == GDCM_UNFOUND ) {
928       nb = 16;
929    } else {
930       nb = atoi(str_nb.c_str() );
931       if (nb == 12) nb =16;  // ?? 12 should be ACR-NEMA only ?
932    }
933
934    int nBytes= nb/8;
935    
936    int taille = Header->GetXSize() * Header->GetYSize()  
937                * Header->GetSamplesPerPixel();    
938    long fragmentBegining; // for ftell, fseek
939
940    bool jpg2000 =     Header->IsJPEG2000();
941    bool jpgLossless = Header->IsJPEGLossless();
942     
943    bool res = true;
944    guint16 ItemTagGr,ItemTagEl;
945    int ln;  
946    
947    //  Position on begining of Jpeg Pixels
948    
949    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
950    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
951    if(Header->GetSwapCode()) {
952       ItemTagGr=Header->SwapShort(ItemTagGr); 
953       ItemTagEl=Header->SwapShort(ItemTagEl);            
954    }
955    fread(&ln,4,1,fp); 
956    if(Header->GetSwapCode()) 
957       ln=Header->SwapLong(ln);    // Basic Offset Table Item length
958       
959    if (ln != 0) {
960       // What is it used for ?!?
961       char *BasicOffsetTableItemValue = (char *)malloc(ln+1);        
962       fread(BasicOffsetTableItemValue,ln,1,fp); 
963    }
964    
965    // first Fragment initialisation
966    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
967    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
968    if(Header->GetSwapCode()) {
969       ItemTagGr=Header->SwapShort(ItemTagGr); 
970       ItemTagEl=Header->SwapShort(ItemTagEl);            
971    }
972            
973    // parsing fragments until Sequence Delim. Tag found
974    while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) { 
975       // --- for each Fragment
976
977       fread(&ln,4,1,fp); 
978       if(Header->GetSwapCode()) 
979          ln=Header->SwapLong(ln);    // Fragment Item length
980    
981       fragmentBegining=ftell(fp);   
982
983       if (jpg2000) {          // JPEG 2000 :    call to ???
984  
985          res = (bool)gdcm_read_JPEG2000_file (fp,destination);  // Not Yet written 
986
987       } // ------------------------------------- endif (JPEG2000)
988         
989       else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
990                    
991          JPEGLosslessDecodeImage (fp,  // Reading Fragment pixels
992                                      (unsigned short *)destination,
993                                      Header->GetPixelSize()*8* Header->GetSamplesPerPixel(),
994                                      ln);                                                          
995          res=1; // in order not to break the loop
996   
997       } // ------------------------------------- endif (JPEGLossless)
998                
999       else {                   // JPEG Lossy : call to IJG 6b
1000
1001          if  (Header->GetBitsStored() == 8) {
1002             res = (bool)gdcm_read_JPEG_file (fp,destination);  // Reading Fragment pixels         
1003          } else {
1004             res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels  
1005          } 
1006       }  // ------------------------------------- endif (JPEGLossy)    
1007          
1008       if (!res) break;
1009                
1010       destination = (char *)destination + taille * nBytes; // location in user's memory 
1011                                                            // for next fragment (if any) 
1012       
1013       fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start 
1014       fseek(fp,ln,SEEK_CUR);               // at the begining of next fragment
1015       
1016       ItemTagGr = ItemTagEl =0;
1017       fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
1018       fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
1019       if(Header->GetSwapCode()) {
1020          ItemTagGr=Header->SwapShort(ItemTagGr); 
1021          ItemTagEl=Header->SwapShort(ItemTagEl);            
1022       } 
1023    
1024    }     // endWhile parsing fragments until Sequence Delim. Tag found    
1025  
1026    Header->CloseFile();
1027    return res;
1028 }
1029 //-----------------------------------------------------------------------------