]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
comments added
[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     
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    PixelRead=0; // no PixelRaw
200    return(PixelData);
201 }
202
203 /**
204  * \ingroup gdcmFile
205  * \brief   Copies at most MaxSize bytes of pixel data to caller's
206  *          memory space.
207  * \warning This function was designed to avoid people that want to build
208  *          a volume from an image stack to need first to get the image pixels 
209  *          and then move them to the volume area.
210  *          It's absolutely useless for any VTK user since vtk chooses 
211  *          to invert the lines of an image, that is the last line comes first
212  *          (for some axis related reasons?). Hence he will have 
213  *          to load the image line by line, starting from the end.
214  *          VTK users have to call GetImageData
215  *     
216  * @param   destination Address (in caller's memory space) at which the
217  *          pixel data should be copied
218  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
219  *          is not sufficient to hold the pixel data the copy is not
220  *          executed (i.e. no partial copy).
221  * @return  On success, the number of bytes actually copied. Zero on
222  *          failure e.g. MaxSize is lower than necessary.
223  */
224 size_t gdcmFile::GetImageDataIntoVector (void* destination, size_t MaxSize) {
225    size_t l = GetImageDataIntoVectorRaw (destination, MaxSize);
226    PixelRead=0 ; // no PixelRaw
227    if (!Header->HasLUT())
228       return lgrTotale; 
229                             
230    // from Lut R + Lut G + Lut B
231    unsigned char * newDest = (unsigned char *)malloc(lgrTotale);
232    unsigned char * a       = (unsigned char *)destination;       
233    unsigned char * lutRGBA =                  Header->GetLUTRGBA();
234    if (lutRGBA) {           
235       int l = lgrTotaleRaw;
236       memmove(newDest, destination, l);// move Gray pixels to temp area     
237       int j;     
238       for (int i=0;i<l; i++) {         // Build RGB Pixels
239          j=newDest[i]*4;
240          *a++ = lutRGBA[j]; 
241          *a++ = lutRGBA[j+1];
242          *a++ = lutRGBA[j+2];
243       }
244       free(newDest);
245     
246    // now, it's an RGB image
247    // Lets's write it in the Header
248
249          // CreateOrReplaceIfExist ?
250          
251    std::string spp = "3";        // Samples Per Pixel
252    Header->SetEntryByNumber(spp,0x0028,0x0002);
253    std::string rgb= "RGB ";      // Photometric Interpretation
254    Header->SetEntryByNumber(rgb,0x0028,0x0004);
255    std::string planConfig = "0"; // Planar Configuration
256    Header->SetEntryByNumber(planConfig,0x0028,0x0006);
257
258    } else { 
259              // need to make RGB Pixels (?)
260              //    from grey Pixels (?!)
261              //     and Gray Lut  (!?!) 
262              //    or Segmented xxx Palette Color Lookup Table Data and so on
263                                                   
264          // Oops! I get one (gdcm-US-ALOKA-16.dcm)
265          // No idea how to manage such an image 
266          // It seems that *no Dicom Viewer* has any idea :-(
267          // Segmented xxx Palette Color are *more* than 65535 long ?!?
268                    
269       std::string rgb= "MONOCHROME1 ";      // Photometric Interpretation
270       Header->SetEntryByNumber(rgb,0x0028,0x0004);                                 
271    }             
272    // TODO : Drop Palette Color out of the Header?           
273    return lgrTotale; 
274 }
275
276 /**
277  * \ingroup gdcmFile
278  * \brief   Allocates necessary memory, copies the pixel data
279  *          (image[s]/volume[s]) to newly allocated zone.
280  *          Transforms YBR pixels into RGB pixels if any
281  *          Transforms 3 planes R, G, B into a single RGB Plane
282  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
283  * @return  Pointer to newly allocated pixel data.
284  * \        NULL if alloc fails 
285  */
286 void * gdcmFile::GetImageDataRaw (void) {
287    if (Header->HasLUT())
288       lgrTotale /= 3;  // TODO Let gdcmHeadar user a chance 
289                        // to get the right value
290                        // Create a member lgrTotaleRaw ???
291    PixelData = (void *) malloc(lgrTotale);
292    if (PixelData)
293       GetImageDataIntoVectorRaw(PixelData, lgrTotale);
294    PixelRead=1; // PixelRaw
295    return(PixelData);
296 }
297
298 /**
299  * \ingroup gdcmFile
300  * \brief   Copies at most MaxSize bytes of pixel data to caller's
301  *          memory space.
302  * \warning This function was designed to avoid people that want to build
303  *          a volume from an image stack to need first to get the image pixels 
304  *          and then move them to the volume area.
305  *          It's absolutely useless for any VTK user since vtk chooses 
306  *          to invert the lines of an image, that is the last line comes first
307  *          (for some axis related reasons?). Hence he will have 
308  *          to load the image line by line, starting from the end.
309  *          VTK users hace to call GetImageData
310  * \warning DOES NOT transform the Grey Plane + Palette Color (if any) 
311  *                   into a single RGB Pixels Plane
312  *          the (VTK) user will manage the palettes
313  *     
314  * @param   destination Address (in caller's memory space) at which the
315  *          pixel data should be copied
316  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
317  *          is not sufficient to hold the pixel data the copy is not
318  *          executed (i.e. no partial copy).
319  * @return  On success, the number of bytes actually copied. Zero on
320  *          failure e.g. MaxSize is lower than necessary.
321  */
322 size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t MaxSize) {
323
324    int nb, nbu, highBit, signe;
325    std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
326    PixelRead=1 ; // PixelRaw
327  
328    if ( lgrTotale > MaxSize ) {
329       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
330                      "than caller's expected MaxSize");
331       return (size_t)0; 
332    }
333         
334    (void)ReadPixelData(destination);
335         
336         // Number of Bits Allocated for storing a Pixel
337    str_nb = Header->GetEntryByNumber(0x0028,0x0100);
338    if (str_nb == GDCM_UNFOUND ) {
339       nb = 16;
340    } else {
341       nb = atoi(str_nb.c_str() );
342    }    
343         // Number of Bits actually used
344    str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
345    if (str_nbu == GDCM_UNFOUND ) {
346       nbu = nb;
347    } else {
348       nbu = atoi(str_nbu.c_str() );
349    }            
350         // High Bit Position
351    str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
352    if (str_highBit == GDCM_UNFOUND ) {
353       highBit = nb - 1;
354    } else {
355       highBit = atoi(str_highBit.c_str() );
356    }            
357         // Pixel sign
358         // 0 = Unsigned
359         // 1 = Signed
360    str_signe=Header->GetEntryByNumber(0x0028,0x0103);
361    if (str_signe == GDCM_UNFOUND ) {
362       signe = 0;  // default is unsigned
363    } else {
364       signe = atoi(str_signe.c_str() );
365    }
366
367    // re arange bytes inside the integer (processor endianity)
368    if (nb != 8)
369      SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
370      
371    // to avoid pb with some xmedcon breakers images 
372    if (nb==16 && nbu<nb && signe==0) {
373      int l = (int)lgrTotale / (nb/8);
374      guint16 *deb = (guint16 *)destination;
375      for(int i = 0; i<l; i++) {
376         if(*deb == 0xffff) 
377            *deb=0; 
378            deb++;   
379          }
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 code commented out.
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;i++)
776             ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
777                                         | ((((unsigned short int*)im)[i])<<8);
778          break;
779                         
780       default:
781          printf("SWAP value (16 bits) not allowed : %d\n", swap);
782    } 
783  
784 if( nb == 32 )
785    switch (swap) {
786       case 0:
787       case 1234:
788          break;
789
790       case 4321:
791          for(i=0;i<lgr;i++) {
792             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
793             fort  =((unsigned long int*)im)[i]>>16;
794             fort=  (fort>>8)   | (fort<<8);
795             faible=(faible>>8) | (faible<<8);
796             s32=faible;
797             ((unsigned long int*)im)[i]=(s32<<16)|fort;
798          }
799          break;
800
801       case 2143:
802          for(i=0;i<lgr;i++) {
803             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
804             fort=((unsigned long int*)im)[i]>>16;
805             fort=  (fort>>8)   | (fort<<8);
806             faible=(faible>>8) | (faible<<8);
807             s32=fort; 
808             ((unsigned long int*)im)[i]=(s32<<16)|faible;
809          }
810          break;
811   
812       case 3412:
813          for(i=0;i<lgr;i++) {
814             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
815             fort=((unsigned long int*)im)[i]>>16;                  
816             s32=faible; 
817             ((unsigned long int*)im)[i]=(s32<<16)|fort;
818          }                 
819          break; 
820                                 
821       default:
822          printf("SWAP value (32 bits) not allowed : %d\n", swap);
823    } 
824 return;
825 }
826
827 /**
828  * \ingroup gdcmFile
829  * \brief   Read pixel data from disk (optionaly decompressing) into the
830  *          caller specified memory location.
831  * @param   destination where the pixel data should be stored.
832  *
833  */
834 bool gdcmFile::ReadPixelData(void* destination) {
835
836    FILE *fp;
837
838    if ( !(fp=Header->OpenFile()))
839       return false;
840    if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
841       Header->CloseFile();
842       return false;
843    }
844    // ----------------------  Compacted File (12 Bits Per Pixel)
845    /* unpack 12 Bits pixels into 16 Bits pixels */
846    /* 2 pixels 12bit =     [0xABCDEF]           */
847    /* 2 pixels 16bit = [0x0ABD] + [0x0FCE]      */
848    
849    if (Header->GetBitsAllocated()==12) {
850       int nbPixels = Header->GetXSize() * Header->GetYSize();
851       unsigned char b0, b1, b2;
852       
853       unsigned short int* pdestination = (unsigned short int*)destination;    
854       for(int p=0;p<nbPixels;p+=2) {
855          fread(&b0,1,1,fp);
856          fread(&b1,1,1,fp);
857          fread(&b2,1,1,fp);      
858          //Two steps is necessary to please VC++
859          *pdestination++ =  ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
860                               /* A */            /* B */             /* D */
861          *pdestination++ =  ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
862                              /* F */               /* C */           /* E */
863                   
864         // Troubles expected on Big-Endian processors ?       
865       }
866
867       Header->CloseFile();
868       return(true);
869    }        
870
871    // ----------------------  Uncompressed File
872    if ( !Header->IsDicomV3()                             ||
873         Header->IsImplicitVRLittleEndianTransferSyntax() ||
874         Header->IsExplicitVRLittleEndianTransferSyntax() ||
875         Header->IsExplicitVRBigEndianTransferSyntax()    ||
876         Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
877
878       size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
879       if ( ItemRead != 1 ) {
880          Header->CloseFile();
881          return false;
882       } else {
883          Header->CloseFile();
884          return true;
885       }
886    } 
887
888    // ---------------------- Run Length Encoding
889    if (Header->IsRLELossLessTransferSyntax()) {
890       bool res = (bool)gdcm_read_RLE_file (fp,destination);
891       Header->CloseFile();
892       return res; 
893    }  
894     
895    // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000 
896    int nb;
897    std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
898    if (str_nb == GDCM_UNFOUND ) {
899       nb = 16;
900    } else {
901       nb = atoi(str_nb.c_str() );
902       if (nb == 12) nb =16;  // ?? 12 should be ACR-NEMA only ?
903    }
904
905    int nBytes= nb/8;
906    
907    int taille = Header->GetXSize() * Header->GetYSize()  
908                * Header->GetSamplesPerPixel();    
909    long fragmentBegining; // for ftell, fseek
910
911    bool jpg2000 =     Header->IsJPEG2000();
912    bool jpgLossless = Header->IsJPEGLossless();
913     
914    bool res = true;
915    guint16 ItemTagGr,ItemTagEl;
916    int ln;  
917    
918    //  Position on begining of Jpeg Pixels
919    
920    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
921    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
922    if(Header->GetSwapCode()) {
923       ItemTagGr=Header->SwapShort(ItemTagGr); 
924       ItemTagEl=Header->SwapShort(ItemTagEl);            
925    }
926    fread(&ln,4,1,fp); 
927    if(Header->GetSwapCode()) 
928       ln=Header->SwapLong(ln);    // Basic Offset Table Item length
929       
930    if (ln != 0) {
931       // What is it used for ?!?
932       char *BasicOffsetTableItemValue = (char *)malloc(ln+1);        
933       fread(BasicOffsetTableItemValue,ln,1,fp); 
934    }
935    
936    // first Fragment initialisation
937    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
938    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
939    if(Header->GetSwapCode()) {
940       ItemTagGr=Header->SwapShort(ItemTagGr); 
941       ItemTagEl=Header->SwapShort(ItemTagEl);            
942    }
943            
944    // parsing fragments until Sequence Delim. Tag found
945    while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) { 
946       // --- for each Fragment
947
948       fread(&ln,4,1,fp); 
949       if(Header->GetSwapCode()) 
950          ln=Header->SwapLong(ln);    // Fragment Item length
951    
952       fragmentBegining=ftell(fp);   
953
954       if (jpg2000) {          // JPEG 2000 :    call to ???
955  
956          res = (bool)gdcm_read_JPEG2000_file (fp,destination);  // Not Yet written 
957
958       } // ------------------------------------- endif (JPEG2000)
959         
960       else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
961                    
962          JPEGLosslessDecodeImage (fp,  // Reading Fragment pixels
963                                      (unsigned short *)destination,
964                                      Header->GetPixelSize()*8* Header->GetSamplesPerPixel(),
965                                      ln);                                                          
966          res=1; // in order not to break the loop
967   
968       } // ------------------------------------- endif (JPEGLossless)
969                
970       else {                   // JPEG Lossy : call to IJG 6b
971
972          if  (Header->GetBitsStored() == 8) {
973             res = (bool)gdcm_read_JPEG_file (fp,destination);  // Reading Fragment pixels         
974          } else {
975             res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels  
976          } 
977       }  // ------------------------------------- endif (JPEGLossy)    
978          
979       if (!res) break;
980                
981       destination = (char *)destination + taille * nBytes; // location in user's memory 
982                                                            // for next fragment (if any) 
983       
984       fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start 
985       fseek(fp,ln,SEEK_CUR);               // at the begining of next fragment
986       
987       ItemTagGr = ItemTagEl =0;
988       fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
989       fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
990       if(Header->GetSwapCode()) {
991          ItemTagGr=Header->SwapShort(ItemTagGr); 
992          ItemTagEl=Header->SwapShort(ItemTagEl);            
993       } 
994    
995    }     // endWhile parsing fragments until Sequence Delim. Tag found    
996  
997    Header->CloseFile();
998    return res;
999 }
1000 //-----------------------------------------------------------------------------