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