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