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