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