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