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