]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
*FIX: Change GetLUTRGBA to return unsigned char instead of void, nicer for python...
[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 =                  GetLUTRGBA();
376    if (lutRGBA) {           
377       int l = lgrTotaleRaw;
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    return lgrTotale; 
421 }
422
423
424
425 /**
426  * \ingroup gdcmFile
427  * \brief   Copies at most MaxSize bytes of pixel data to caller's
428  *          memory space.
429  * \warning This function was designed to avoid people that want to build
430  *          a volume from an image stack to need first to get the image pixels 
431  *          and then move them to the volume area.
432  *          It's absolutely useless for any VTK user since vtk chooses 
433  *          to invert the lines of an image, that is the last line comes first
434  *          (for some axis related reasons?). Hence he will have 
435  *          to load the image line by line, starting from the end.
436  *          VTK users hace to call GetImageData
437   * \warning DOES NOT transform the Grey Plane + Palette Color (if any) 
438  *                   into a single RGB Pixels Plane
439  *          the (VTK) user will manage the palettes
440  *     
441  * @param   destination Address (in caller's memory space) at which the
442  *          pixel data should be copied
443  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
444  *          is not sufficient to hold the pixel data the copy is not
445  *          executed (i.e. no partial copy).
446  * @return  On success, the number of bytes actually copied. Zero on
447  *          failure e.g. MaxSize is lower than necessary.
448  */
449
450 size_t gdcmFile::GetImageDataIntoVectorRaw (void* destination, size_t MaxSize) {
451
452    int nb, nbu, highBit, signe;
453    std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
454  
455    if ( lgrTotale > MaxSize ) {
456       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
457                      "than caller's expected MaxSize");
458       return (size_t)0; 
459    }
460         
461    (void)ReadPixelData(destination);
462                         
463         // Nombre de Bits Alloues pour le stockage d'un Pixel
464    str_nb = GetPubElValByNumber(0x0028,0x0100);
465    if (str_nb == GDCM_UNFOUND ) {
466       nb = 16;
467    } else {
468       nb = atoi(str_nb.c_str() );
469    }
470         
471         // Nombre de Bits Utilises
472    str_nbu=GetPubElValByNumber(0x0028,0x0101);
473    if (str_nbu == GDCM_UNFOUND ) {
474       nbu = nb;
475    } else {
476       nbu = atoi(str_nbu.c_str() );
477    }    
478         
479         // Position du Bit de Poids Fort
480    str_highBit=GetPubElValByNumber(0x0028,0x0102);
481    if (str_highBit == GDCM_UNFOUND ) {
482       highBit = nb - 1;
483    } else {
484       highBit = atoi(str_highBit.c_str() );
485    }            
486         // Pixel sign
487         // 0 = Unsigned
488         // 1 = Signed
489    str_signe=GetPubElValByNumber(0x0028,0x0103);
490    if (str_signe == GDCM_UNFOUND ) {
491       signe = 0;  // default is unsigned
492    } else {
493       signe = atoi(str_signe.c_str() );
494    }
495
496    // re arange bytes inside the integer
497    if (nb != 8)
498      SwapZone(destination, GetSwapCode(), lgrTotale, nb);
499      
500    // to avoid pb with some xmedcon breakers images 
501    if (nb==16 && nbu<nb && signe==0) {
502      int l = (int)lgrTotale / (nb/8);
503      guint16 *deb = (guint16 *)destination;
504      for(int i = 0; i<l; i++) {
505         if(*deb == 0xffff) 
506            *deb=0; 
507            deb++;   
508          }
509     }
510
511    // re arange bits inside the bytes
512    if (nbu != nb){
513       int l = (int)lgrTotale / (nb/8);
514       if (nb == 16) {
515          guint16 mask = 0xffff;
516          mask = mask >> (nb-nbu);
517          guint16 *deb = (guint16 *)destination;
518          for(int i = 0; i<l; i++) {
519             *deb = (*deb >> (nbu-highBit-1)) & mask;
520             deb ++;
521          }
522       } else if (nb == 32 ) {
523          guint32 mask = 0xffffffff;
524          mask = mask >> (nb-nbu);
525          guint32 *deb = (guint32 *)destination;
526          for(int i = 0; i<l; i++) {
527             *deb = (*deb >> (nbu-highBit-1)) & mask;
528             deb ++;
529          }
530       } else {
531          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
532          return (size_t)0; 
533       }
534    } 
535
536 // Just to 'see' what was actually read on disk :-(
537 // Some troubles expected
538 //   FILE * f2;
539 //   f2 = fopen("SpuriousFile.raw","wb");
540 //   fwrite(destination,lgrTotale,1,f2);
541 //   fclose(f2);
542
543    // Deal with the color
544    // -------------------
545    
546        std::string str_PhotometricInterpretation = 
547                  gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
548                    
549       if ( (str_PhotometricInterpretation == "MONOCHROME1 ") 
550         || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
551          return lgrTotale; 
552       }
553       
554    // Planar configuration = 0 : Pixels are already RGB
555    // Planar configuration = 1 : 3 planes : R, G, B
556    // Planar configuration = 2 : 1 gray Plane + 3 LUT
557
558    // Well ... supposed to be !
559    // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
560    //                            PhotometricInterpretation=PALETTE COLOR
561    // and heuristic has to be found :-( 
562
563       int planConf=GetPlanarConfiguration();  // 0028,0006
564
565       // Whatever Planar Configuration is, 
566       // "PALETTE COLOR " implies that we deal with the palette. 
567       if (str_PhotometricInterpretation == "PALETTE COLOR ")
568          planConf=2;
569
570       switch (planConf) {
571       case 0:                              
572          //       Pixels are already RGB
573          break;
574     
575       case 1:
576
577          {
578          if (str_PhotometricInterpretation == "YBR_FULL") { 
579          
580          // Warning : YBR_FULL_422 acts as RGB
581          //         : we need to make RGB Pixels from Planes Y,cB,cR
582          // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
583          // for code optimisation
584          
585          // to see the tricks about YBR_FULL, YBR_FULL_422, 
586          // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
587          //   ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
588          // and be *very* affraid
589          //
590             int l = GetXSize()*GetYSize();
591             int nbFrames = GetZSize();
592
593             unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
594             unsigned char *x  = newDest;
595             unsigned char * a = (unsigned char *)destination;
596             unsigned char * b = a + l;
597             unsigned char * c = b + l;
598
599             double R,G,B;
600
601             // TODO : Replace by the 'well known' 
602             //        integer computation counterpart
603             for (int i=0;i<nbFrames;i++) {
604                for (int j=0;j<l; j++) {
605                   R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
606                   G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
607                   B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
608
609                   if (R<0.0)   R=0.0;
610                   if (G<0.0)   G=0.0;
611                   if (B<0.0)   B=0.0;
612                   if (R>255.0) R=255.0;
613                   if (G>255.0) G=255.0;
614                   if (B>255.0) B=255.0;
615
616                   *(x++) = (unsigned char)R;
617                   *(x++) = (unsigned char)G;
618                   *(x++) = (unsigned char)B;
619                   a++; b++; c++;  
620                }
621            }
622             memmove(destination,newDest,lgrTotale);
623             free(newDest);
624
625         } else {
626          
627          //       need to make RGB Pixels from R,G,B Planes
628          //       (all the Frames at a time)
629
630             int l = GetXSize()*GetYSize()*GetZSize();
631
632             char * newDest = (char*) malloc(lgrTotale);
633             char * x = newDest;
634             char * a = (char *)destination;
635             char * b = a + l;
636             char * c = b + l;
637
638             for (int j=0;j<l; j++) {
639                *(x++) = *(a++);
640                *(x++) = *(b++);
641                *(x++) = *(c++);  
642             }
643            
644             memmove(destination,newDest,lgrTotale);
645             free(newDest);
646         }
647           
648          break;
649        }
650      
651        case 2:                      
652          //       Palettes were found
653          //       Let the user deal with them !
654           return lgrTotale;        
655    } 
656             // now, it's an RGB image
657             // Lets's write it in the Header
658
659          // CreateOrReplaceIfExist ?
660          
661
662
663    std::string spp = "3";        // Samples Per Pixel
664    gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
665    std::string rgb="RGB ";   // Photometric Interpretation
666    gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
667
668    std::string planConfig = "0"; // Planar Configuration
669    gdcmHeader::SetPubElValByNumber(planConfig,0x0028,0x0006);
670          
671          // TODO : Drop Palette Color out of the Header? 
672              
673    return lgrTotale; 
674 }
675
676
677
678 /**
679  * \ingroup gdcmFile
680  * \brief   Swap the bytes, according to swap code.
681  * \warning not end user intended
682  * @param   im area to deal with
683  * @param   swap swap code
684  * @param   lgr Area Length
685  * @param   nb Pixels Bit number 
686  */
687
688 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
689 guint32 s32;
690 guint16 fort,faible;
691 int i;
692
693 if(nb == 16)  
694    switch(swap) {
695       case 0:
696       case 12:
697       case 1234:
698          break;
699                 
700       case 21:
701       case 3412:
702       case 2143:
703       case 4321:
704
705          for(i=0;i<lgr;i++)
706             ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
707                                         | ((((unsigned short int*)im)[i])<<8);
708          break;
709                         
710       default:
711          printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
712    } 
713  
714 if( nb == 32 )
715    switch (swap) {
716       case 0:
717       case 1234:
718          break;
719
720       case 4321:
721          for(i=0;i<lgr;i++) {
722             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
723             fort  =((unsigned long int*)im)[i]>>16;
724             fort=  (fort>>8)   | (fort<<8);
725             faible=(faible>>8) | (faible<<8);
726             s32=faible;
727             ((unsigned long int*)im)[i]=(s32<<16)|fort;
728          }
729          break;
730
731       case 2143:
732          for(i=0;i<lgr;i++) {
733             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
734             fort=((unsigned long int*)im)[i]>>16;
735             fort=  (fort>>8)   | (fort<<8);
736             faible=(faible>>8) | (faible<<8);
737             s32=fort; 
738             ((unsigned long int*)im)[i]=(s32<<16)|faible;
739          }
740          break;
741   
742       case 3412:
743          for(i=0;i<lgr;i++) {
744             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
745             fort=((unsigned long int*)im)[i]>>16;                  
746             s32=faible; 
747             ((unsigned long int*)im)[i]=(s32<<16)|fort;
748          }                 
749          break; 
750                                 
751       default:
752          printf(" SWAP value (32 bits) not allowed : %d\n", swap);
753    } 
754 return;
755 }
756
757 /////////////////////////////////////////////////////////////////
758 /**
759  * \ingroup   gdcmFile
760  * \brief TODO JPR
761  * \warning doit-etre etre publique ?  
762  * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
763  *
764  * @param inData 
765  * @param ExpectedSize 
766  *
767  * @return integer acts as a boolean    
768  */
769 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
770    SetImageDataSize(ExpectedSize);
771    PixelData = inData;
772    lgrTotale = ExpectedSize;
773    return(1);
774 }
775
776
777 /////////////////////////////////////////////////////////////////
778 /**
779  * \ingroup   gdcmFile
780  * \brief Sets the Pixel Area size in the Header
781  *        --> not-for-rats function
782  * 
783  * \warning WARNING doit-etre etre publique ? 
784  * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
785  *
786  * @param ImageDataSize new Pixel Area Size
787  *        warning : nothing else is checked
788  */
789
790 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
791    std::string content1;
792    char car[20];        
793    // Assumes ElValue (0x7fe0, 0x0010) exists ...       
794    sprintf(car,"%d",ImageDataSize);
795  
796    gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
797    a->SetLength(ImageDataSize);
798                 
799    ImageDataSize+=8;
800    sprintf(car,"%d",ImageDataSize);
801    content1=car;        
802    SetPubElValByNumber(content1, 0x7fe0, 0x0000);
803 }
804
805
806 /////////////////////////////////////////////////////////////////
807 /**
808  * \ingroup   gdcmFile
809  * \brief Ecrit sur disque les pixels d'UNE image
810  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
811  *        Ca sera à l'utilisateur d'appeler son Reader correctement
812  *        (Equivalent a IdImaWriteRawFile) 
813  *
814  * @param fileName 
815  * @return      
816  */
817
818 int gdcmFile::WriteRawData (std::string fileName) {
819    FILE * fp1;
820    fp1 = fopen(fileName.c_str(),"wb");
821    if (fp1 == NULL) {
822       printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
823       return (0);
824    }    
825    fwrite (PixelData,lgrTotale, 1, fp1);
826    fclose (fp1);
827    return(1);
828 }
829
830 /////////////////////////////////////////////////////////////////
831 /**
832  * \ingroup   gdcmFile
833  * \brief Ecrit sur disque UNE image Dicom
834  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
835  *         Ca fonctionnera correctement (?) sur processeur Intel
836  *         (Equivalent a IdDcmWrite) 
837  *
838  * @param fileName 
839  * @return int acts as a boolean
840  */
841
842 int gdcmFile::WriteDcmImplVR (std::string fileName) {
843    return WriteBase(fileName, ImplicitVR);
844 }
845
846 /////////////////////////////////////////////////////////////////
847 /**
848  * \ingroup   gdcmFile
849  * \brief  
850  * @param  fileName 
851  * @return int acts as a boolean
852  */
853  
854 int gdcmFile::WriteDcmImplVR (const char* fileName) {
855    return WriteDcmImplVR (std::string (fileName));
856 }
857         
858 /////////////////////////////////////////////////////////////////
859 /**
860  * \ingroup   gdcmFile
861  * \brief  
862  * @param  fileName
863  * @return int acts as a boolean
864  */
865
866 int gdcmFile::WriteDcmExplVR (std::string fileName) {
867    return WriteBase(fileName, ExplicitVR);
868 }
869         
870 /////////////////////////////////////////////////////////////////
871 /**
872  * \ingroup   gdcmFile
873  * \brief  Ecrit au format ACR-NEMA sur disque l'entete et les pixels
874  *        (a l'attention des logiciels cliniques 
875  *        qui ne prennent en entrée QUE des images ACR ...
876  * \warning si un header DICOM est fourni en entree,
877  *        les groupes < 0x0008 et les groupes impairs sont ignores)
878  * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
879  *        Ca fonctionnera correctement (?) sur processeur Intel
880  *        (Equivalent a IdDcmWrite) 
881  *
882  * @param fileName
883  * @return int acts as a boolean        
884  */
885
886 int gdcmFile::WriteAcr (std::string fileName) {
887    return WriteBase(fileName, ACR);
888 }
889
890 /////////////////////////////////////////////////////////////////
891 /**
892  * \ingroup   gdcmFile
893  *
894  * @param  FileName
895  * @param  type 
896  *
897  * @return int acts as a boolean
898  */
899 int gdcmFile::WriteBase (std::string FileName, FileType type) {
900
901    FILE * fp1;
902    fp1 = fopen(FileName.c_str(),"wb");
903    if (fp1 == NULL) {
904       printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
905       return (0);
906    }
907
908    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
909       char * filePreamble;
910       // writing Dicom File Preamble
911       filePreamble=(char*)calloc(128,1);
912       fwrite(filePreamble,128,1,fp1);
913       fwrite("DICM",4,1,fp1);
914    }
915
916    // --------------------------------------------------------------
917    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
918    //
919    // if recognition code tells us we dealt with a LibIDO image
920    // we reproduce on disk the switch between lineNumber and columnNumber
921    // just before writting ...
922
923    std::string rows, columns; 
924    if ( filetype == ACR_LIBIDO){
925          rows    = GetPubElValByNumber(0x0028, 0x0010);
926          columns = GetPubElValByNumber(0x0028, 0x0011);
927          SetPubElValByNumber(columns,  0x0028, 0x0010);
928          SetPubElValByNumber(rows   ,  0x0028, 0x0011);
929    }    
930    // ----------------- End of Special Patch ----------------
931
932    gdcmHeader::Write(fp1, type);
933
934    // --------------------------------------------------------------
935    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
936    // 
937    // ...and we restore the Header to be Dicom Compliant again 
938    // just after writting
939
940    if (filetype == ACR_LIBIDO){
941          SetPubElValByNumber(rows   , 0x0028, 0x0010);
942          SetPubElValByNumber(columns, 0x0028, 0x0011);
943    }    
944    // ----------------- End of Special Patch ----------------
945
946    fwrite(PixelData, lgrTotale, 1, fp1);
947    fclose (fp1);
948    return(1);
949 }