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