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