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