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