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