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