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