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