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