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