]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
removal of now useless LibIDO Jpeg Lossless .h and .cxx
[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    str_signe=GetPubElValByNumber(0x0028,0x0103);
358    if (str_signe == GDCM_UNFOUND ) {
359       signe = 1;
360    } else {
361       signe = atoi(str_signe.c_str() );
362    }
363
364    // re arange bytes inside the integer
365    if (nb != 8)
366      SwapZone(destination, GetSwapCode(), lgrTotale, nb);
367  
368    // re arange bits inside the bytes
369    if (nbu != nb){
370       int l = (int)lgrTotale / (nb/8);
371       if (nb == 16) {
372          guint16 mask = 0xffff;
373          mask = mask >> (nb-nbu);
374          guint16 *deb = (guint16 *)destination;
375          for(int i = 0; i<l; i++) {
376             *deb = (*deb >> (nbu-highBit-1)) & mask;
377             deb ++;
378          }
379       } else if (nb == 32 ) {
380          guint32 mask = 0xffffffff;
381          mask = mask >> (nb-nbu);
382          guint32 *deb = (guint32 *)destination;
383          for(int i = 0; i<l; i++) {
384             *deb = (*deb >> (nbu-highBit-1)) & mask;
385             deb ++;
386          }
387       } else {
388          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: wierd image");
389          return (size_t)0; 
390       }
391    } 
392
393 // Just to 'see' was was actually read on disk :-(
394 // Some troubles expected
395
396    // *Try* to deal with the color
397    // ----------------------------
398    
399        std::string str_PhotometricInterpretation = 
400                  gdcmHeader::GetPubElValByNumber(0x0028,0x0004);
401                    
402       if ( (str_PhotometricInterpretation == "MONOCHROME1 ") 
403         || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
404          return lgrTotale; 
405       }
406       
407    // Planar configuration = 0 : Pixels are already RGB
408    // Planar configuration = 1 : 3 planes : R, G, B
409    // Planar configuration = 2 : 1 gray Plane + 3 LUT
410
411    // Well ... supposed to be !
412    // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
413    //                            PhotometricInterpretation=PALETTE COLOR
414    // and heuristic has to be found :-( 
415
416       int planConf=GetPlanarConfiguration();  // 0028,0006
417
418       // Whatever Planar Configuration is, 
419       // "PALETTE COLOR " implies that we deal with the palette. 
420       if (str_PhotometricInterpretation == "PALETTE COLOR ")
421          planConf=2;
422
423       switch (planConf) {
424       case 0:                              
425          //       Pixels are already RGB
426          break;
427     
428       case 1:
429
430          {
431          if (str_PhotometricInterpretation == "YBR_FULL") { // Warning : YBR_FULL_422 acts as RGB (?!)
432
433          //       need to make RGB Pixels from Planes Y,cB,cR
434          // see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
435          // for code optimisation
436
437             int l = GetXSize()*GetYSize();
438             int nbFrames = GetZSize();
439
440             unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
441             unsigned char *x  = newDest;
442             unsigned char * a = (unsigned char *)destination;
443             unsigned char * b = a + l;
444             unsigned char * c = b + l;
445
446             double R,G,B;
447
448             // TODO : Replace by the 'well known' 
449             //        integer computation counterpart
450             for (int i=0;i<nbFrames;i++) {
451                for (int j=0;j<l; j++) {
452                   R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
453                   G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
454                   B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
455
456                   if (R<0.0)   R=0.0;
457                   if (G<0.0)   G=0.0;
458                   if (B<0.0)   B=0.0;
459                   if (R>255.0) R=255.0;
460                   if (G>255.0) G=255.0;
461                   if (B>255.0) B=255.0;
462
463                   *(x++) = (unsigned char)R;
464                   *(x++) = (unsigned char)G;
465                   *(x++) = (unsigned char)B;
466                   a++; b++; c++;  
467                }
468            }
469             memmove(destination,newDest,lgrTotale);
470             free(newDest);
471
472         } else {
473          
474          //       need to make RGB Pixels from Planes R,G,B
475
476             int l = GetXSize()*GetYSize();
477             int nbFrames = GetZSize();
478
479             char * newDest = (char*) malloc(lgrTotale);
480             char *x  = newDest;
481             char * a = (char *)destination;
482             char * b = a + l;
483             char * c = b + l;
484
485                // TODO :
486                // any trick not to have to allocate temporary buffer is welcome ...
487
488             for (int i=0;i<nbFrames;i++) {
489                for (int j=0;j<l; j++) {
490                   *(x++) = *(a++);
491                   *(x++) = *(b++);
492                   *(x++) = *(c++);  
493                }
494             }
495             memmove(destination,newDest,lgrTotale);
496             free(newDest);
497         }
498           
499          break;
500        }
501      
502        case 2:                      
503          //       from Lut R + Lut G + Lut B
504        
505          // we no longer use gdcmHeader::GetLUTRGB
506          // since a lot of images have strange info 
507          // in the Lookup Table Descriptors (0028,1101),...
508          {
509          unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
510          unsigned char * a = (unsigned char *)destination;
511
512          unsigned char *lutR =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1201);
513          unsigned char *lutG =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1202);
514          unsigned char *lutB =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1203);
515
516          if (lutR && lutG && lutB ) { // need to make RGB Pixels 
517                                       // from grey Pixels 
518                                       // and Lut R,Lut G,Lut B
519
520             unsigned char * newDest = (unsigned char*) malloc(lgrTotale);
521             int l = lgrTotale/3;
522             memmove(newDest, destination, l);// move Gray pixels to temp area
523
524             int j;
525                // See PS 3.3-2003 C.11.1.1.2 p 619
526                // 
527             int mult;
528             if (GetLUTNbits()==16 && nb==8) mult=2; // See PS 3.3 
529             else mult=1;
530
531             // if we get a black image, let's just remove the '+1'
532             // and check again 
533             // if it works, we shall have to check the 3 Palettes
534             // to see which byte is ==0 (first one, or second one)
535                            
536             for (int i=0;i<l; i++) {
537                j=newDest[i]*mult +1;
538                *a++ = lutR[j]; 
539                *a++ = lutG[j];
540                *a++ = lutB[j];
541             }
542
543             free(newDest);
544                
545          } else { 
546              // need to make RGB Pixels (?)
547              // from grey Pixels (?!)
548              // and Gray Lut  (!?!) 
549              //unsigned char *lutGray =(unsigned char *)GetPubElValVoidAreaByNumber(0x0028,0x1200);
550                   
551                              // Well . I'll wait till I find such an image 
552                   
553              // or Segmented Green Palette Color Lookup Table Data and so on
554                   
555                             // Oops! I get one (gdcm-US-ALOKA-16.dcm)
556                             // No idea how to manage it :-(
557                             // Segmented xxx Palette Color are *more* than 65535 long ?!?
558                             
559             // WARNING : quick and dirty trick to produce a single plane Grey image
560             // See also  gdcmHeaderHelper::GetNumberOfScalarComponents()                              
561                     lgrTotale /=3;
562                     return lgrTotale;
563             // end of dirty trick
564          }
565          break;
566       }
567    } 
568
569             // now, it's an RGB image
570             // Lets's write it in the Header
571
572          // CreateOrReplaceIfExist ?
573          
574    std::string spp = "3";        // Samples Per Pixel
575    gdcmHeader::SetPubElValByNumber(spp,0x0028,0x0002);
576    std::string rgb="RGB ";       // Photometric Interpretation
577    gdcmHeader::SetPubElValByNumber(rgb,0x0028,0x0004);
578    std::string planConfig = "0"; // Planar Configuration
579    gdcmHeader::SetPubElValByNumber(planConfig,0x0028,0x0006);
580          
581          // + Drop Palette Color ? 
582              
583    return lgrTotale; 
584 }
585
586 //
587 // Je laisse le code integral, au cas ça puisse etre reutilise ailleurs
588 //
589
590 /**
591  * \ingroup gdcmFile
592  * \brief   Swap the bytes, according to swap code.
593  * \warning not end user intended
594  * @param   im area to deal with
595  * @param   swap swap code
596  * @param   lgr Area Length
597  * @param   nb Pixels Bit number 
598  */
599
600 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb) {
601 guint32 s32;
602 guint16 fort,faible;
603 int i;
604
605 if(nb == 16)  
606    switch(swap) {
607       case 0:
608       case 12:
609       case 1234:
610          break;
611                 
612       case 21:
613       case 3412:
614       case 2143:
615       case 4321:
616
617          for(i=0;i<lgr;i++)
618             ((unsigned short int*)im)[i]= ((((unsigned short int*)im)[i])>>8)
619                                         | ((((unsigned short int*)im)[i])<<8);
620          break;
621                         
622       default:
623          printf("valeur de SWAP (16 bits) not allowed : %d\n", swap);
624    } 
625  
626 if( nb == 32 )
627    switch (swap) {
628       case 0:
629       case 1234:
630          break;
631
632       case 4321:
633          for(i=0;i<lgr;i++) {
634             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 4321 */
635             fort  =((unsigned long int*)im)[i]>>16;
636             fort=  (fort>>8)   | (fort<<8);
637             faible=(faible>>8) | (faible<<8);
638             s32=faible;
639             ((unsigned long int*)im)[i]=(s32<<16)|fort;
640          }
641          break;
642
643       case 2143:
644          for(i=0;i<lgr;i++) {
645             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 2143 */
646             fort=((unsigned long int*)im)[i]>>16;
647             fort=  (fort>>8)   | (fort<<8);
648             faible=(faible>>8) | (faible<<8);
649             s32=fort; 
650             ((unsigned long int*)im)[i]=(s32<<16)|faible;
651          }
652          break;
653   
654       case 3412:
655          for(i=0;i<lgr;i++) {
656             faible=  ((unsigned long int*)im)[i]&0x0000ffff;    /* 3412 */
657             fort=((unsigned long int*)im)[i]>>16;                  
658             s32=faible; 
659             ((unsigned long int*)im)[i]=(s32<<16)|fort;
660          }                 
661          break; 
662                                 
663       default:
664          printf(" SWAP value (32 bits) not allowed : %d\n", swap);
665    } 
666 return;
667 }
668
669 /////////////////////////////////////////////////////////////////
670 /**
671  * \ingroup   gdcmFile
672  * \brief TODO JPR
673  * \warning doit-etre etre publique ?  
674  * TODO : y a-t-il un inconvenient à fusioner ces 2 fonctions
675  *
676  * @param inData 
677  * @param ExpectedSize 
678  *
679  * @return integer acts as a boolean    
680  */
681 int gdcmFile::SetImageData(void * inData, size_t ExpectedSize) {
682    SetImageDataSize(ExpectedSize);
683    PixelData = inData;
684    lgrTotale = ExpectedSize;
685    return(1);
686 }
687
688
689 /////////////////////////////////////////////////////////////////
690 /**
691  * \ingroup   gdcmFile
692  * \brief Sets the Pixel Area size in the Header
693  *        --> not-for-rats function
694  * 
695  * \warning WARNING doit-etre etre publique ? 
696  * TODO : y aurait il un inconvenient à fusionner ces 2 fonctions
697  *
698  * @param ImageDataSize new Pixel Area Size
699  *        warning : nothing else is checked
700  */
701
702 void gdcmFile::SetImageDataSize(size_t ImageDataSize) {
703    std::string content1;
704    char car[20];        
705    // Assumes ElValue (0x7fe0, 0x0010) exists ...       
706    sprintf(car,"%d",ImageDataSize);
707  
708    gdcmElValue*a = GetElValueByNumber(0x7fe0, 0x0010);
709    a->SetLength(ImageDataSize);
710                 
711    ImageDataSize+=8;
712    sprintf(car,"%d",ImageDataSize);
713    content1=car;        
714    SetPubElValByNumber(content1, 0x7fe0, 0x0000);
715 }
716
717
718 /////////////////////////////////////////////////////////////////
719 /**
720  * \ingroup   gdcmFile
721  * \brief Ecrit sur disque les pixels d'UNE image
722  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
723  *        Ca sera à l'utilisateur d'appeler son Reader correctement
724  *        (Equivalent a IdImaWriteRawFile) 
725  *
726  * @param fileName 
727  * @return      
728  */
729
730 int gdcmFile::WriteRawData (std::string fileName) {
731    FILE * fp1;
732    fp1 = fopen(fileName.c_str(),"wb");
733    if (fp1 == NULL) {
734       printf("Echec ouverture (ecriture) Fichier [%s] \n",fileName.c_str());
735       return (0);
736    }    
737    fwrite (PixelData,lgrTotale, 1, fp1);
738    fclose (fp1);
739    return(1);
740 }
741
742 /////////////////////////////////////////////////////////////////
743 /**
744  * \ingroup   gdcmFile
745  * \brief Ecrit sur disque UNE image Dicom
746  *        Aucun test n'est fait sur l'"Endiannerie" du processeur.
747  *         Ca fonctionnera correctement (?) sur processeur Intel
748  *         (Equivalent a IdDcmWrite) 
749  *
750  * @param fileName 
751  * @return int acts as a boolean
752  */
753
754 int gdcmFile::WriteDcmImplVR (std::string fileName) {
755    return WriteBase(fileName, ImplicitVR);
756 }
757
758 /////////////////////////////////////////////////////////////////
759 /**
760  * \ingroup   gdcmFile
761  * \brief  
762  * @param  fileName 
763  * @return int acts as a boolean
764  */
765  
766 int gdcmFile::WriteDcmImplVR (const char* fileName) {
767    return WriteDcmImplVR (std::string (fileName));
768 }
769         
770 /////////////////////////////////////////////////////////////////
771 /**
772  * \ingroup   gdcmFile
773  * \brief  
774  * @param  fileName
775  * @return int acts as a boolean
776  */
777
778 int gdcmFile::WriteDcmExplVR (std::string fileName) {
779    return WriteBase(fileName, ExplicitVR);
780 }
781         
782 /////////////////////////////////////////////////////////////////
783 /**
784  * \ingroup   gdcmFile
785  * \brief  Ecrit au format ACR-NEMA sur disque l'entete et les pixels
786  *        (a l'attention des logiciels cliniques 
787  *        qui ne prennent en entrée QUE des images ACR ...
788  * \warning si un header DICOM est fourni en entree,
789  *        les groupes < 0x0008 et les groupes impairs sont ignores)
790  * \warning Aucun test n'est fait sur l'"Endiannerie" du processeur.
791  *        Ca fonctionnera correctement (?) sur processeur Intel
792  *        (Equivalent a IdDcmWrite) 
793  *
794  * @param fileName
795  * @return int acts as a boolean        
796  */
797
798 int gdcmFile::WriteAcr (std::string fileName) {
799    return WriteBase(fileName, ACR);
800 }
801
802 /////////////////////////////////////////////////////////////////
803 /**
804  * \ingroup   gdcmFile
805  *
806  * @param  FileName
807  * @param  type 
808  *
809  * @return int acts as a boolean
810  */
811 int gdcmFile::WriteBase (std::string FileName, FileType type) {
812
813    FILE * fp1;
814    fp1 = fopen(FileName.c_str(),"wb");
815    if (fp1 == NULL) {
816       printf("Echec ouverture (ecriture) Fichier [%s] \n",FileName.c_str());
817       return (0);
818    }
819
820    if ( (type == ImplicitVR) || (type == ExplicitVR) ) {
821       char * filePreamble;
822       // writing Dicom File Preamble
823       filePreamble=(char*)calloc(128,1);
824       fwrite(filePreamble,128,1,fp1);
825       fwrite("DICM",4,1,fp1);
826    }
827
828    // --------------------------------------------------------------
829    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
830    //
831    // if recognition code tells us we dealt with a LibIDO image
832    // we reproduce on disk the switch between lineNumber and columnNumber
833    // just before writting ...
834
835    std::string rows, columns; 
836    if ( filetype == ACR_LIBIDO){
837          rows    = GetPubElValByNumber(0x0028, 0x0010);
838          columns = GetPubElValByNumber(0x0028, 0x0011);
839          SetPubElValByNumber(columns,  0x0028, 0x0010);
840          SetPubElValByNumber(rows   ,  0x0028, 0x0011);
841    }    
842    // ----------------- End of Special Patch ----------------
843
844    gdcmHeader::Write(fp1, type);
845
846    // --------------------------------------------------------------
847    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
848    // 
849    // ...and we restore the Header to be Dicom Compliant again 
850    // just after writting
851
852    if (filetype == ACR_LIBIDO){
853          SetPubElValByNumber(rows   , 0x0028, 0x0010);
854          SetPubElValByNumber(columns, 0x0028, 0x0011);
855    }    
856    // ----------------- End of Special Patch ----------------
857
858    fwrite(PixelData, lgrTotale, 1, fp1);
859    fclose (fp1);
860    return(1);
861 }