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