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