]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
44579afa9b691c5fe3dda825c9fc480292882f8f
[gdcm.git] / src / gdcmFile.cxx
1 /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/06/25 17:48:45 $
7   Version:   $Revision: 1.110 $
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() {
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() {
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() {
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() {
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 () {
197    PixelData = new unsigned char[lgrTotale];  //consistant with GetImageDataIntoVector
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
242    if (lutRGBA) {
243       int l = lgrTotaleRaw;
244       memmove(newDest, destination, l);// move Gray pixels to temp area  
245       int j;
246       for (int i=0;i<l; i++) {         // Build RGB Pixels
247          j=newDest[i]*4;
248          *a++ = lutRGBA[j]; 
249          *a++ = lutRGBA[j+1];
250          *a++ = lutRGBA[j+2];
251       }
252       delete[] newDest;
253     
254    // now, it's an RGB image
255    // Lets's write it in the Header
256
257          // CreateOrReplaceIfExist ?
258
259    std::string spp = "3";        // Samples Per Pixel
260    Header->SetEntryByNumber(spp,0x0028,0x0002);
261    std::string rgb= "RGB ";      // Photometric Interpretation
262    Header->SetEntryByNumber(rgb,0x0028,0x0004);
263    std::string planConfig = "0"; // Planar Configuration
264    Header->SetEntryByNumber(planConfig,0x0028,0x0006);
265
266    } else { 
267         // need to make RGB Pixels (?)
268         //    from grey Pixels (?!)
269         //     and Gray Lut  (!?!) 
270         //    or Segmented xxx Palette Color Lookup Table Data and so on
271  
272          // Oops! I get one (gdcm-US-ALOKA-16.dcm)
273          // No idea how to manage such an image 
274          // It seems that *no Dicom Viewer* has any idea :-(
275          // Segmented xxx Palette Color are *more* than 65535 long ?!?
276   
277       std::string rgb= "MONOCHROME1 ";      // Photometric Interpretation
278       Header->SetEntryByNumber(rgb,0x0028,0x0004);
279    } 
280    /// \todo Drop Palette Color out of the Header?
281    return lgrTotale; 
282 }
283
284 /**
285  * \ingroup gdcmFile
286  * \brief   Allocates necessary memory, copies the pixel data
287  *          (image[s]/volume[s]) to newly allocated zone.
288  *          Transforms YBR pixels into RGB pixels if any
289  *          Transforms 3 planes R, G, B into a single RGB Plane
290  *          DOES NOT transform Grey plane + 3 Palettes into a RGB Plane
291  * @return  Pointer to newly allocated pixel data.
292  * \        NULL if alloc fails 
293  */
294 void * gdcmFile::GetImageDataRaw () {
295    if (Header->HasLUT())
296       /// \todo Let gdcmHeader user a chance to get the right value
297       /// Create a member lgrTotaleRaw ???
298       lgrTotale /= 3;
299    PixelData = new unsigned char[lgrTotale];
300
301    if (PixelData) {
302       GetImageDataIntoVectorRaw(PixelData, lgrTotale);
303       GetHeader()->SetEntryVoidAreaByNumber(PixelData, 
304       GetHeader()->GetGrPixel(),  
305       GetHeader()->GetNumPixel()); 
306    } 
307    PixelRead=1; // PixelRaw
308
309    return PixelData;
310 }
311
312 /**
313  * \ingroup gdcmFile
314  * \brief   Copies at most MaxSize bytes of pixel data to caller's
315  *          memory space.
316  * \warning This function was designed to avoid people that want to build
317  *          a volume from an image stack to need first to get the image pixels 
318  *          and then move them to the volume area.
319  *          It's absolutely useless for any VTK user since vtk chooses 
320  *          to invert the lines of an image, that is the last line comes first
321  *          (for some axis related reasons?). Hence he will have 
322  *          to load the image line by line, starting from the end.
323  *          VTK users hace to call GetImageData
324  * \warning DOES NOT transform the Grey Plane + Palette Color (if any) 
325  *                   into a single RGB Pixels Plane
326  *          the (VTK) user will manage the palettes
327  *     
328  * @param   destination Address (in caller's memory space) at which the
329  *          pixel data should be copied
330  * @param   MaxSize Maximum number of bytes to be copied. When MaxSize
331  *          is not sufficient to hold the pixel data the copy is not
332  *          executed (i.e. no partial copy).
333  * @return  On success, the number of bytes actually copied. Zero on
334  *          failure e.g. MaxSize is lower than necessary.
335  */
336 size_t gdcmFile::GetImageDataIntoVectorRaw (void *destination, size_t MaxSize) {
337
338    int nb, nbu, highBit, signe;
339    std::string str_nbFrames, str_nb, str_nbu, str_highBit, str_signe;
340    PixelRead=1 ; // PixelRaw
341  
342    if ( lgrTotale > MaxSize ) {
343       dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: pixel data bigger"
344                      "than caller's expected MaxSize");
345       return (size_t)0; 
346    }
347
348    ReadPixelData(destination);
349
350    // Number of Bits Allocated for storing a Pixel
351    str_nb = Header->GetEntryByNumber(0x0028,0x0100);
352    if (str_nb == GDCM_UNFOUND ) {
353       nb = 16;
354    } else {
355       nb = atoi(str_nb.c_str() );
356  }
357     // Number of Bits actually used
358    str_nbu=Header->GetEntryByNumber(0x0028,0x0101);
359    if (str_nbu == GDCM_UNFOUND ) {
360       nbu = nb;
361    } else {
362       nbu = atoi(str_nbu.c_str() );
363    }
364    // High Bit Position
365    str_highBit=Header->GetEntryByNumber(0x0028,0x0102);
366    if (str_highBit == GDCM_UNFOUND ) {
367       highBit = nb - 1;
368    } else {
369       highBit = atoi(str_highBit.c_str() );
370    } 
371    // Pixel sign
372    // 0 = Unsigned
373    // 1 = Signed
374    str_signe=Header->GetEntryByNumber(0x0028,0x0103);
375    if (str_signe == GDCM_UNFOUND ) {
376       signe = 0;  // default is unsigned
377    } else {
378       signe = atoi(str_signe.c_str() );
379    }
380
381    // re arange bytes inside the integer (processor endianity)
382    if (nb != 8)
383      SwapZone(destination, Header->GetSwapCode(), lgrTotale, nb);
384      
385    // to avoid pb with some xmedcon breakers images 
386    if (nb==16 && nbu<nb && signe==0) {
387      int l = (int)lgrTotale / (nb/8);
388      guint16 *deb = (guint16 *)destination;
389      for(int i = 0; i<l; i++) {
390         if(*deb == 0xffff) 
391            *deb=0; 
392            deb++;   
393          }
394     }
395    // re arange bits inside the bytes
396    if (nbu != nb){
397       int l = (int)lgrTotale / (nb/8);
398       if (nb == 16) {
399          guint16 mask = 0xffff;
400          mask = mask >> (nb-nbu);
401          guint16 *deb = (guint16 *)destination;
402          for(int i = 0; i<l; i++) {
403             *deb = (*deb >> (nbu-highBit-1)) & mask;
404             deb ++;
405          }
406       } else if (nb == 32 ) {
407          guint32 mask = 0xffffffff;
408          mask = mask >> (nb-nbu);
409          guint32 *deb = (guint32 *)destination;
410          for(int i = 0; i<l; i++) {
411             *deb = (*deb >> (nbu-highBit-1)) & mask;
412             deb ++;
413          }
414       } else {
415          dbg.Verbose(0, "gdcmFile::GetImageDataIntoVector: weird image");
416          return 0;
417       }
418    } 
419 // DO NOT remove this commented out code .
420 // Nobody knows what's expecting you ...
421 // Just to 'see' what was actually read on disk :-(
422
423 //   FILE * f2;
424 //   f2 = fopen("SpuriousFile.RAW","wb");
425 //   fwrite(destination,lgrTotale,1,f2);
426 //   fclose(f2);
427
428    // Deal with the color
429    // -------------------
430    
431        std::string str_PhotometricInterpretation = 
432                  Header->GetEntryByNumber(0x0028,0x0004);
433
434       if ( (str_PhotometricInterpretation == "MONOCHROME1 ") 
435         || (str_PhotometricInterpretation == "MONOCHROME2 ") ) {
436          return lgrTotale; 
437       }
438       
439    // Planar configuration = 0 : Pixels are already RGB
440    // Planar configuration = 1 : 3 planes : R, G, B
441    // Planar configuration = 2 : 1 gray Plane + 3 LUT
442
443    // Well ... supposed to be !
444    // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
445    //                            PhotometricInterpretation=PALETTE COLOR
446    // and heuristic has to be found :-( 
447
448       int planConf=Header->GetPlanarConfiguration();  // 0028,0006
449
450       // Whatever Planar Configuration is, 
451       // "PALETTE COLOR " implies that we deal with the palette. 
452       if (str_PhotometricInterpretation == "PALETTE COLOR ")
453          planConf=2;
454
455       switch (planConf) {
456       case 0:                              
457          //       Pixels are already RGB
458          break;
459     
460       case 1:
461
462          {
463          if (str_PhotometricInterpretation == "YBR_FULL") { 
464  
465    // Warning : YBR_FULL_422 acts as RGB
466    //         : we need to make RGB Pixels from Planes Y,cB,cR
467
468    // to see the tricks about YBR_FULL, YBR_FULL_422, 
469    // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
470    //   ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
471    // and be *very* affraid
472    //
473             int l = Header->GetXSize()*Header->GetYSize();
474             int nbFrames = Header->GetZSize();
475
476             unsigned char *newDest = new unsigned char[lgrTotale];
477             unsigned char *x = newDest;
478             unsigned char *a = (unsigned char *)destination;
479             unsigned char *b = a + l;
480             unsigned char *c = b + l;
481             double R,G,B;
482
483             /// \todo : Replace by the 'well known' integer computation
484             /// counterpart
485             /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
486             /// for code optimisation
487     
488             for (int i=0;i<nbFrames;i++) {
489                for (int j=0;j<l; j++) {
490                   R= 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
491                   G= 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
492                   B= 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
493
494                   if (R<0.0)   R=0.0;
495                   if (G<0.0)   G=0.0;
496                   if (B<0.0)   B=0.0;
497                   if (R>255.0) R=255.0;
498                   if (G>255.0) G=255.0;
499                   if (B>255.0) B=255.0;
500
501                   *(x++) = (unsigned char)R;
502                   *(x++) = (unsigned char)G;
503                   *(x++) = (unsigned char)B;
504                   a++; b++; c++;  
505                }
506            }
507             memmove(destination,newDest,lgrTotale);
508             delete[] newDest;
509
510         } else {
511          
512          //       need to make RGB Pixels from R,G,B Planes
513          //       (all the Frames at a time)
514
515             int l = Header->GetXSize()*Header->GetYSize()*Header->GetZSize();
516
517             char *newDest = new char[lgrTotale];
518             char *x = newDest;
519             char *a = (char *)destination;
520             char *b = a + l;
521             char *c = b + l;
522
523             for (int j=0;j<l; j++) {
524                *(x++) = *(a++);
525                *(x++) = *(b++);
526                *(x++) = *(c++);  
527             }           
528             memmove(destination,newDest,lgrTotale);
529             delete[] newDest;
530         }  
531          break;
532        }     
533        case 2:                      
534          //       Palettes were found
535          //       Let the user deal with them !
536          return lgrTotale;        
537    } 
538    // now, it's an RGB image
539    // Lets's write it in the Header
540
541    // CreateOrReplaceIfExist ?
542
543    std::string spp = "3";        // Samples Per Pixel
544    Header->SetEntryByNumber(spp,0x0028,0x0002);
545    std::string rgb="RGB ";   // Photometric Interpretation
546    Header->SetEntryByNumber(rgb,0x0028,0x0004);
547
548    std::string planConfig = "0"; // Planar Configuration
549    Header->SetEntryByNumber(planConfig,0x0028,0x0006);
550  
551  /// \todo Drop Palette Color out of the Header? 
552    return lgrTotale; 
553 }
554
555 /**
556  * \ingroup   gdcmFile
557  * \brief performs a shalow copy (not a deep copy) of the user given
558  *        pixel area.
559  *        'image' Pixels are presented as C-like 2D arrays : line per line.
560  *        'volume'Pixels are presented as C-like 3D arrays : lane per plane 
561  * \warning user is kindly requested NOT TO 'free' the Pixel area
562  * @param inData user supplied pixel area
563  * @param ExpectedSize total image size, in Bytes
564  *
565  * @return boolean
566  */
567 bool gdcmFile::SetImageData(void *inData, size_t ExpectedSize) {
568    Header->SetImageDataSize(ExpectedSize);
569    PixelData = inData;
570    lgrTotale = ExpectedSize;
571    PixelRead = 1;
572
573    return true;
574 }
575
576 /**
577  * \ingroup   gdcmFile
578  * \brief Writes on disk A SINGLE Dicom file
579  *        NO test is performed on  processor "Endiannity".
580  *        It's up to the user to call his Reader properly
581  * @param fileName name of the file to be created
582  *                 (any already existing file is over written)
583  * @return false if write fails
584  */
585
586 bool gdcmFile::WriteRawData (std::string const & fileName) {
587    FILE *fp1;
588    fp1 = fopen(fileName.c_str(),"wb");
589    if (fp1 == NULL) {
590       printf("Fail to open (write) file [%s] \n",fileName.c_str());
591       return false;
592    }
593    fwrite (PixelData,lgrTotale, 1, fp1);
594    fclose (fp1);
595
596    return true;
597 }
598
599 /**
600  * \ingroup   gdcmFile
601  * \brief Writes on disk A SINGLE Dicom file, 
602  *        using the Implicit Value Representation convention
603  *        NO test is performed on  processor "Endiannity".
604  * @param fileName name of the file to be created
605  *                 (any already existing file is overwritten)
606  * @return false if write fails
607  */
608
609 bool gdcmFile::WriteDcmImplVR (std::string const & fileName) {
610    return WriteBase(fileName, gdcmImplicitVR);
611 }
612
613 /**
614  * \ingroup   gdcmFile
615 * \brief Writes on disk A SINGLE Dicom file, 
616  *        using the Explicit Value Representation convention
617  *        NO test is performed on  processor "Endiannity". * @param fileName name of the file to be created
618  *                 (any already existing file is overwritten)
619  * @return false if write fails
620  */
621
622 bool gdcmFile::WriteDcmExplVR (std::string const & fileName) {
623    return WriteBase(fileName, gdcmExplicitVR);
624 }
625
626 /**
627  * \ingroup   gdcmFile
628  * \brief Writes on disk A SINGLE Dicom file, 
629  *        using the ACR-NEMA convention
630  *        NO test is performed on  processor "Endiannity".
631  *        (a l'attention des logiciels cliniques 
632  *        qui ne prennent en entrée QUE des images ACR ...
633  * \warning if a DICOM_V3 header is supplied,
634  *         groups < 0x0008 and shadow groups are ignored
635  * \warning NO TEST is performed on processor "Endiannity".
636  * @param fileName name of the file to be created
637  *                 (any already existing file is overwritten)
638  * @return false if write fails
639  */
640
641 bool gdcmFile::WriteAcr (std::string const & fileName) {
642    return WriteBase(fileName, gdcmACR);
643 }
644
645 //-----------------------------------------------------------------------------
646 // Protected
647 /**
648  * \ingroup   gdcmFile
649  * \brief NOT a end user inteded function
650  *        (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
651  * @param fileName name of the file to be created
652  *                 (any already existing file is overwritten)
653  * @param  type file type (ExplicitVR, ImplicitVR, ...)
654  * @return false if write fails
655  */
656 bool gdcmFile::WriteBase (std::string const & fileName, FileType type) {
657
658    FILE *fp1;
659    
660    if (PixelRead==-1 && type != gdcmExplicitVR) {
661       return false;
662    }
663
664    fp1 = fopen(fileName.c_str(),"wb");
665    if (fp1 == NULL) {
666       printf("Failed to open (write) File [%s] \n",fileName.c_str());
667       return (false);
668    }
669
670    if ( (type == gdcmImplicitVR) || (type == gdcmExplicitVR) ) {
671       char *filePreamble;
672       // writing Dicom File Preamble
673       filePreamble=new char[128];
674       memset(filePreamble,0,128);
675       fwrite(filePreamble,128,1,fp1);
676       fwrite("DICM",4,1,fp1);
677       delete[] filePreamble;
678    }
679
680    // --------------------------------------------------------------
681    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
682    //
683    // if recognition code tells us we dealt with a LibIDO image
684    // we reproduce on disk the switch between lineNumber and columnNumber
685    // just before writting ...
686    
687    /// \todo the best trick would be *change* the recognition code
688    ///       but pb expected if user deals with, e.g. COMPLEX images
689
690    std::string rows, columns; 
691    if ( Header->GetFileType() == gdcmACR_LIBIDO){
692          rows    = Header->GetEntryByNumber(0x0028, 0x0010);
693          columns = Header->GetEntryByNumber(0x0028, 0x0011);
694          Header->SetEntryByNumber(columns,  0x0028, 0x0010);
695          Header->SetEntryByNumber(rows   ,  0x0028, 0x0011);
696    }
697    // ----------------- End of Special Patch ----------------
698    
699    /// \todo get the grPixel, numPixel values (for some ACR-NEMA images only)
700    
701    guint16 grPixel =Header->GetGrPixel();
702    guint16 numPixel=Header->GetNumPixel();;
703     
704    // Update Pixel Data Length
705    // the *last* of the (GrPixel, NumPixel), if many.
706           
707    TagKey key = gdcmDictEntry::TranslateToKey(grPixel, numPixel); 
708    TagDocEntryHT::iterator p2;
709    gdcmDocEntry *PixelElement;
710    
711    IterHT it= Header->GetEntry().equal_range(key); // get a pair of iterators first-last synonym   
712
713    if (Header->GetEntry().count(key) == 1) // only the first is significant
714       p2=it.first; // iterator on the first (unique) synonym
715    else
716       p2=it.second;// iterator on the last synonym
717    
718    PixelElement=p2->second;        // H Table target column (2-nd col)
719   // PixelElement->SetPrintLevel(2);
720   // PixelElement->Print();      
721  
722    if (PixelRead==1)
723       PixelElement->SetLength(lgrTotaleRaw);
724    else if (PixelRead==0)
725       PixelElement->SetLength(lgrTotale);
726    
727    //PixelElement->SetPrintLevel(2);
728    //PixelElement->Print();    
729    Header->Write(fp1, type);
730
731    // --------------------------------------------------------------
732    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
733    // 
734    // ...and we restore the Header to be Dicom Compliant again 
735    // just after writting
736
737    if (Header->GetFileType() == gdcmACR_LIBIDO){
738          Header->SetEntryByNumber(rows   , 0x0028, 0x0010);
739          Header->SetEntryByNumber(columns, 0x0028, 0x0011);
740    }
741    // ----------------- End of Special Patch ----------------
742    
743   // fwrite(PixelData, lgrTotale, 1, fp1);  // should be useless, now
744    fclose (fp1);
745
746    return true;
747 }
748
749 //-----------------------------------------------------------------------------
750 // Private
751 /**
752  * \ingroup gdcmFile
753  * \brief   Swap the bytes, according to swap code.
754  * \warning not end user intended
755  * @param   im area to deal with
756  * @param   swap swap code
757  * @param   lgr Area Length
758  * @param   nb Pixels Bit number 
759  */
760 void gdcmFile::SwapZone(void *im, int swap, int lgr, int nb) {
761   guint32 s32;
762   guint16 fort,faible;
763   int i;
764
765   if(nb == 16)  
766      switch(swap) {
767       case 0:
768       case 12:
769       case 1234:
770          break;
771
772       case 21:
773       case 3412:
774       case 2143:
775       case 4321:
776
777          for(i=0;i<lgr/2;i++) {
778             ((unsigned short int *)im)[i]= ((((unsigned short int *)im)[i])>>8)
779                                         | ((((unsigned short int *)im)[i])<<8);
780          }
781          break;
782
783       default:
784           std::cout << "SWAP value (16 bits) not allowed :i" << swap << std::endl;
785    } 
786  
787   if( nb == 32 )
788      switch (swap) {
789       case 0:
790       case 1234:
791          break;
792
793       case 4321:
794          for(i=0;i<lgr/4;i++) {
795             faible=  ((unsigned long int *)im)[i]&0x0000ffff;    /* 4321 */
796             fort  =((unsigned long int *)im)[i]>>16;
797             fort=  (fort>>8)   | (fort<<8);
798             faible=(faible>>8) | (faible<<8);
799             s32=faible;
800             ((unsigned long int *)im)[i]=(s32<<16)|fort;
801          }
802          break;
803
804       case 2143:
805          for(i=0;i<lgr/4;i++) {
806             faible=  ((unsigned long int *)im)[i]&0x0000ffff;    /* 2143 */
807             fort=((unsigned long int *)im)[i]>>16;
808             fort=  (fort>>8)   | (fort<<8);
809             faible=(faible>>8) | (faible<<8);
810             s32=fort; 
811             ((unsigned long int *)im)[i]=(s32<<16)|faible;
812          }
813          break;
814   
815       case 3412:
816          for(i=0;i<lgr/4;i++) {
817             faible=  ((unsigned long int *)im)[i]&0x0000ffff;    /* 3412 */
818             fort=((unsigned long int *)im)[i]>>16;                  
819             s32=faible; 
820             ((unsigned long int *)im)[i]=(s32<<16)|fort;
821          }                 
822          break; 
823      
824       default:
825          std::cout << "SWAP value (32 bits) not allowed : " << swap << std::endl;
826    } 
827 }
828
829 /**
830  * \ingroup gdcmFile
831  * \brief   Read pixel data from disk (optionaly decompressing) into the
832  *          caller specified memory location.
833  * @param   destination where the pixel data should be stored.
834  *
835  */
836 bool gdcmFile::ReadPixelData(void *destination) {
837
838    FILE *fp;
839
840    if ( !(fp=Header->OpenFile()))
841       return false;
842    if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 ) {
843       Header->CloseFile();
844       return false;
845    }
846    // ----------------------  Compacted File (12 Bits Per Pixel)
847    /* unpack 12 Bits pixels into 16 Bits pixels */
848    /* 2 pixels 12bit =     [0xABCDEF]           */
849    /* 2 pixels 16bit = [0x0ABD] + [0x0FCE]      */
850    
851    if (Header->GetBitsAllocated()==12) {
852       int nbPixels = Header->GetXSize() * Header->GetYSize();
853       unsigned char b0, b1, b2;
854       
855       unsigned short int *pdestination = (unsigned short int*)destination;    
856       for(int p=0;p<nbPixels;p+=2) {
857          fread(&b0,1,1,fp);
858          fread(&b1,1,1,fp);
859          fread(&b2,1,1,fp);      
860          //Two steps is necessary to please VC++
861          *pdestination++ =  ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
862                               /* A */            /* B */             /* D */
863          *pdestination++ =  ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
864                              /* F */               /* C */           /* E */
865   
866     // Troubles expected on Big-Endian processors ?
867       }
868
869       Header->CloseFile();
870       return true;
871    }        
872
873    // ----------------------  Uncompressed File
874    if ( !Header->IsDicomV3()                             ||
875         Header->IsImplicitVRLittleEndianTransferSyntax() ||
876         Header->IsExplicitVRLittleEndianTransferSyntax() ||
877         Header->IsExplicitVRBigEndianTransferSyntax()    ||
878         Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() ) {
879
880       size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
881       if ( ItemRead != 1 ) {
882          Header->CloseFile();
883          return false;
884       } else {
885          Header->CloseFile();
886          return true;
887       }
888    } 
889
890    // ---------------------- Run Length Encoding
891    if (Header->IsRLELossLessTransferSyntax()) {
892       bool res = (bool)gdcm_read_RLE_file (fp,destination);
893       Header->CloseFile();
894       return res; 
895    }  
896     
897    // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000 
898    int nb;
899    std::string str_nb=Header->GetEntryByNumber(0x0028,0x0100);
900    if (str_nb == GDCM_UNFOUND ) {
901       nb = 16;
902    } else {
903       nb = atoi(str_nb.c_str() );
904       if (nb == 12) nb =16;  // ?? 12 should be ACR-NEMA only ?
905    }
906
907    int nBytes= nb/8;
908    
909    int taille = Header->GetXSize() * Header->GetYSize()  
910                * Header->GetSamplesPerPixel();    
911    long fragmentBegining; // for ftell, fseek
912
913    bool jpg2000 =     Header->IsJPEG2000();
914    bool jpgLossless = Header->IsJPEGLossless();
915
916    bool res = true;
917    guint16 ItemTagGr,ItemTagEl;
918    int ln;  
919    
920    //  Position on begining of Jpeg Pixels
921    
922    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
923    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
924    if(Header->GetSwapCode()) {
925       ItemTagGr=Header->SwapShort(ItemTagGr); 
926       ItemTagEl=Header->SwapShort(ItemTagEl);            
927    }
928    fread(&ln,4,1,fp); 
929    if(Header->GetSwapCode()) 
930       ln=Header->SwapLong(ln);    // Basic Offset Table Item length
931       
932    if (ln != 0) {
933       // What is it used for ?!?
934       char *BasicOffsetTableItemValue = new char[ln+1];
935       fread(BasicOffsetTableItemValue,ln,1,fp); 
936    }
937    
938    // first Fragment initialisation
939    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
940    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
941    if(Header->GetSwapCode()) {
942       ItemTagGr=Header->SwapShort(ItemTagGr); 
943       ItemTagEl=Header->SwapShort(ItemTagEl);            
944    }
945            
946    // parsing fragments until Sequence Delim. Tag found
947    while ( ( ItemTagGr == 0xfffe) && (ItemTagEl != 0xe0dd) ) { 
948       // --- for each Fragment
949
950       fread(&ln,4,1,fp); 
951       if(Header->GetSwapCode()) 
952          ln=Header->SwapLong(ln);    // Fragment Item length
953    
954       fragmentBegining=ftell(fp);   
955
956       if (jpg2000) {          // JPEG 2000 :    call to ???
957  
958          res = (bool)gdcm_read_JPEG2000_file (fp,destination);  // Not Yet written 
959
960       } // ------------------------------------- endif (JPEG2000)
961
962       else if (jpgLossless) { // JPEG LossLess : call to xmedcom JPEG
963          JPEGLosslessDecodeImage (fp,  // Reading Fragment pixels
964                                   (unsigned short *)destination,
965                                    Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(),
966                                      ln);
967          res=1; // in order not to break the loop
968   
969       } // ------------------------------------- endif (JPEGLossless)
970                
971       else {                   // JPEG Lossy : call to IJG 6b
972
973          if  (Header->GetBitsStored() == 8) {
974             res = (bool)gdcm_read_JPEG_file (fp,destination);  // Reading Fragment pixels         
975          } else {
976             res = (bool)gdcm_read_JPEG_file12 (fp,destination);// Reading Fragment pixels  
977          } 
978       }  // ------------------------------------- endif (JPEGLossy)    
979          
980       if (!res) break;
981                
982       destination = (char *)destination + taille * nBytes; // location in user's memory 
983                                                            // for next fragment (if any) 
984       
985       fseek(fp,fragmentBegining,SEEK_SET); // To be sure we start 
986       fseek(fp,ln,SEEK_CUR);               // at the begining of next fragment
987       
988       ItemTagGr = ItemTagEl =0;
989       fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
990       fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
991       if(Header->GetSwapCode()) {
992          ItemTagGr=Header->SwapShort(ItemTagGr); 
993          ItemTagEl=Header->SwapShort(ItemTagEl);            
994       } 
995    
996    }     // endWhile parsing fragments until Sequence Delim. Tag found    
997  
998    Header->CloseFile();
999    return res;
1000 }
1001 //-----------------------------------------------------------------------------