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