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