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