]> Creatis software - gdcm.git/blob - src/gdcmFile.cxx
Cosmetic modifs to be more Coding style compliant
[gdcm.git] / src / gdcmFile.cxx
1   /*=========================================================================
2                                                                                 
3   Program:   gdcm
4   Module:    $RCSfile: gdcmFile.cxx,v $
5   Language:  C++
6   Date:      $Date: 2004/09/24 11:39:21 $
7   Version:   $Revision: 1.129 $
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 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 // DO NOT remove this code commented out.
669 // Nobody knows what's expecting you ...
670 // Just to 'see' what was actually read on disk :-(
671
672 //   FILE*  f2;
673 //   f2 = fopen("SpuriousFile.RAW","wb");
674 //   fwrite(destination,ImageDataSize,1,f2);
675 //   fclose(f2);
676
677    // Deal with the color
678    // -------------------
679    
680    std::string str_PhotometricInterpretation = 
681       Header->GetEntryByNumber(0x0028,0x0004);
682
683    if ( str_PhotometricInterpretation == "MONOCHROME1 " 
684      || str_PhotometricInterpretation == "MONOCHROME2 " )
685    {
686       return ImageDataSize; 
687    }
688       
689    // Planar configuration = 0 : Pixels are already RGB
690    // Planar configuration = 1 : 3 planes : R, G, B
691    // Planar configuration = 2 : 1 gray Plane + 3 LUT
692
693    // Well ... supposed to be !
694    // See US-PAL-8-10x-echo.dcm: PlanarConfiguration=0,
695    //                            PhotometricInterpretation=PALETTE COLOR
696    // and heuristic has to be found :-( 
697
698    int planConf = Header->GetPlanarConfiguration();  // 0028,0006
699
700    // Whatever Planar Configuration is, 
701    // "PALETTE COLOR " implies that we deal with the palette. 
702    if ( str_PhotometricInterpretation == "PALETTE COLOR ")
703    {
704       planConf = 2;
705    }
706
707    switch ( planConf )
708    {
709       case 0:
710          // Pixels are already RGB
711          break;
712       case 1:
713          if (str_PhotometricInterpretation == "YBR_FULL")
714          {
715             // Warning : YBR_FULL_422 acts as RGB
716             //         : we need to make RGB Pixels from Planes Y,cB,cR
717
718             // to see the tricks about YBR_FULL, YBR_FULL_422, 
719             // YBR_PARTIAL_422, YBR_ICT, YBR_RCT have a look at :
720             // ftp://medical.nema.org/medical/dicom/final/sup61_ft.pdf
721             // and be *very* affraid
722             //
723             int l        = Header->GetXSize() * Header->GetYSize();
724             int nbFrames = Header->GetZSize();
725
726             uint8_t* newDest = new uint8_t[ImageDataSize];
727             uint8_t* x       = newDest;
728             uint8_t* a       = (uint8_t*)destination;
729             uint8_t* b       = a + l;
730             uint8_t* c       = b + l;
731             double R,G,B;
732
733             /// \todo : Replace by the 'well known' integer computation
734             /// counterpart
735             /// see http://lestourtereaux.free.fr/papers/data/yuvrgb.pdf
736             /// for code optimisation
737     
738             for (int i = 0; i < nbFrames; i++)
739             {
740                for (int j = 0; j < l; j++)
741                {
742                   R = 1.164 *(*a-16) + 1.596 *(*c -128) + 0.5;
743                   G = 1.164 *(*a-16) - 0.813 *(*c -128) - 0.392 *(*b -128) + 0.5;
744                   B = 1.164 *(*a-16) + 2.017 *(*b -128) + 0.5;
745
746                   if (R < 0.0)   R = 0.0;
747                   if (G < 0.0)   G = 0.0;
748                   if (B < 0.0)   B = 0.0;
749                   if (R > 255.0) R = 255.0;
750                   if (G > 255.0) G = 255.0;
751                   if (B > 255.0) B = 255.0;
752
753                   *(x++) = (uint8_t)R;
754                   *(x++) = (uint8_t)G;
755                   *(x++) = (uint8_t)B;
756                   a++; b++; c++;  
757                }
758             }
759             memmove(destination, newDest, ImageDataSize);
760             delete[] newDest;
761          }
762          else
763          {
764             // need to make RGB Pixels from R,G,B Planes
765             // (all the Frames at a time)
766
767             int l = Header->GetXSize() * Header->GetYSize() * Header->GetZSize();
768
769             uint8_t *newDest = new uint8_t[ImageDataSize];
770             uint8_t *x       = newDest;
771             uint8_t *a       = (uint8_t *)destination;
772             uint8_t *b       = a + l;
773             uint8_t *c       = b + l;
774
775             for (int j = 0; j < l; j++)
776             {
777                *(x++) = *(a++);
778                *(x++) = *(b++);
779                *(x++) = *(c++);
780             }
781             memmove(destination, newDest, ImageDataSize);
782             delete[] newDest;
783          }
784          break;
785       case 2:                      
786          // Palettes were found
787          // Let the user deal with them !
788          return ImageDataSize;
789    }
790    // now, it's an RGB image
791    // Lets's write it in the Header
792  
793    // Droping Palette Color out of the Header
794    // has been moved to the Write process.
795
796    // TODO : move 'values' modification to the write process
797    //      : save also (in order to be able to restore)
798    //      : 'high bit' -when not equal to 'bits stored' + 1
799    //      : 'bits allocated', when it's equal to 12 ?!
800
801    std::string spp = "3";            // Samples Per Pixel
802    std::string photInt = "RGB ";     // Photometric Interpretation
803    std::string planConfig = "0";     // Planar Configuration
804      
805    Header->SetEntryByNumber(spp,0x0028,0x0002);
806    Header->SetEntryByNumber(photInt,0x0028,0x0004);
807    Header->SetEntryByNumber(planConfig,0x0028,0x0006);
808  
809    return ImageDataSize; 
810 }
811
812 /**
813  * \ingroup   gdcmFile
814  * \brief performs a shalow copy (not a deep copy) of the user given
815  *        pixel area.
816  *        'image' Pixels are presented as C-like 2D arrays : line per line.
817  *        'volume'Pixels are presented as C-like 3D arrays : plane per plane 
818  * \warning user is kindly requested NOT TO 'free' the Pixel area
819  * @param inData user supplied pixel area
820  * @param expectedSize total image size, in Bytes
821  *
822  * @return boolean
823  */
824 bool gdcmFile::SetImageData(uint8_t* inData, size_t expectedSize)
825 {
826    Header->SetImageDataSize( expectedSize );
827 // FIXME : if already allocated, memory leak !
828    Pixel_Data     = inData;
829    ImageDataSize = ImageDataSizeRaw = expectedSize;
830    PixelRead     = 1;
831 // FIXME : 7fe0, 0010 IS NOT set ...
832    return true;
833 }
834
835 /**
836  * \ingroup   gdcmFile
837  * \brief Writes on disk A SINGLE Dicom file
838  *        NO test is performed on  processor "Endiannity".
839  *        It's up to the user to call his Reader properly
840  * @param fileName name of the file to be created
841  *                 (any already existing file is over written)
842  * @return false if write fails
843  */
844
845 bool gdcmFile::WriteRawData(std::string const & fileName)
846 {
847    FILE* fp1 = fopen(fileName.c_str(), "wb");
848    if (fp1 == NULL)
849    {
850       printf("Fail to open (write) file [%s] \n", fileName.c_str());
851       return false;
852    }
853    fwrite (Pixel_Data, ImageDataSize, 1, fp1);
854    fclose (fp1);
855
856    return true;
857 }
858
859 /**
860  * \ingroup   gdcmFile
861  * \brief Writes on disk A SINGLE Dicom file, 
862  *        using the Implicit Value Representation convention
863  *        NO test is performed on  processor "Endiannity".
864  * @param fileName name of the file to be created
865  *                 (any already existing file is overwritten)
866  * @return false if write fails
867  */
868
869 bool gdcmFile::WriteDcmImplVR (std::string const & fileName)
870 {
871    return WriteBase(fileName, gdcmImplicitVR);
872 }
873
874 /**
875  * \ingroup   gdcmFile
876 * \brief Writes on disk A SINGLE Dicom file, 
877  *        using the Explicit Value Representation convention
878  *        NO test is performed on  processor "Endiannity". * @param fileName name of the file to be created
879  *                 (any already existing file is overwritten)
880  * @return false if write fails
881  */
882
883 bool gdcmFile::WriteDcmExplVR (std::string const & fileName)
884 {
885    return WriteBase(fileName, gdcmExplicitVR);
886 }
887
888 /**
889  * \ingroup   gdcmFile
890  * \brief Writes on disk A SINGLE Dicom file, 
891  *        using the ACR-NEMA convention
892  *        NO test is performed on  processor "Endiannity".
893  *        (a l'attention des logiciels cliniques 
894  *        qui ne prennent en entrée QUE des images ACR ...
895  * \warning if a DICOM_V3 header is supplied,
896  *         groups < 0x0008 and shadow groups are ignored
897  * \warning NO TEST is performed on processor "Endiannity".
898  * @param fileName name of the file to be created
899  *                 (any already existing file is overwritten)
900  * @return false if write fails
901  */
902
903 bool gdcmFile::WriteAcr (std::string const & fileName)
904 {
905    return WriteBase(fileName, gdcmACR);
906 }
907
908 //-----------------------------------------------------------------------------
909 // Protected
910 /**
911  * \ingroup   gdcmFile
912  * \brief NOT a end user inteded function
913  *        (used by WriteDcmExplVR, WriteDcmImplVR, WriteAcr, etc)
914  * @param fileName name of the file to be created
915  *                 (any already existing file is overwritten)
916  * @param  type file type (ExplicitVR, ImplicitVR, ...)
917  * @return false if write fails
918  */
919 bool gdcmFile::WriteBase (std::string const & fileName, FileType type)
920 {
921    if ( PixelRead == -1 && type != gdcmExplicitVR)
922    {
923       return false;
924    }
925
926    FILE* fp1 = fopen(fileName.c_str(), "wb");
927    if (fp1 == NULL)
928    {
929       printf("Failed to open (write) File [%s] \n", fileName.c_str());
930       return false;
931    }
932
933    if ( type == gdcmImplicitVR || type == gdcmExplicitVR )
934    {
935       // writing Dicom File Preamble
936       uint8_t* filePreamble = new uint8_t[128];
937       memset(filePreamble, 0, 128);
938       fwrite(filePreamble, 128, 1, fp1);
939       fwrite("DICM", 4, 1, fp1);
940
941       delete[] filePreamble;
942    }
943
944    // --------------------------------------------------------------
945    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
946    //
947    // if recognition code tells us we dealt with a LibIDO image
948    // we reproduce on disk the switch between lineNumber and columnNumber
949    // just before writting ...
950    
951    /// \todo the best trick would be *change* the recognition code
952    ///       but pb expected if user deals with, e.g. COMPLEX images
953
954    std::string rows, columns; 
955    if ( Header->GetFileType() == gdcmACR_LIBIDO)
956    {
957       rows    = Header->GetEntryByNumber(0x0028, 0x0010);
958       columns = Header->GetEntryByNumber(0x0028, 0x0011);
959
960       Header->SetEntryByNumber(columns,  0x0028, 0x0010);
961       Header->SetEntryByNumber(rows   ,  0x0028, 0x0011);
962    }
963    // ----------------- End of Special Patch ----------------
964       
965    uint16_t grPixel  = Header->GetGrPixel();
966    uint16_t numPixel = Header->GetNumPixel();;
967           
968    gdcmDocEntry* PixelElement = 
969       GetHeader()->GetDocEntryByNumber(grPixel, numPixel);  
970  
971    if ( PixelRead == 1 )
972    {
973       // we read pixel 'as is' (no tranformation LUT -> RGB)
974       PixelElement->SetLength( ImageDataSizeRaw );
975    }
976    else if ( PixelRead == 0 )
977    {
978       // we tranformed GrayLevel pixels + LUT into RGB Pixel
979       PixelElement->SetLength( ImageDataSize );
980    }
981  
982    Header->Write(fp1, type);
983
984    // --------------------------------------------------------------
985    // Special Patch to allow gdcm to re-write ACR-LibIDO formated images
986    // 
987    // ...and we restore the Header to be Dicom Compliant again 
988    // just after writting
989
990    if ( Header->GetFileType() == gdcmACR_LIBIDO )
991    {
992       Header->SetEntryByNumber(rows   , 0x0028, 0x0010);
993       Header->SetEntryByNumber(columns, 0x0028, 0x0011);
994    }
995    // ----------------- End of Special Patch ----------------
996    
997    // fwrite(Pixel_Data, ImageDataSize, 1, fp1);  // should be useless, now
998    fclose (fp1);
999
1000    return true;
1001 }
1002
1003 //-----------------------------------------------------------------------------
1004 // Private
1005 /**
1006  * \ingroup gdcmFile
1007  * \brief   Swap the bytes, according to swap code.
1008  * \warning not end user intended
1009  * @param   im area to deal with
1010  * @param   swap swap code
1011  * @param   lgr Area Length
1012  * @param   nb Pixels Bit number 
1013  */
1014 void gdcmFile::SwapZone(void* im, int swap, int lgr, int nb)
1015 {
1016    int i;
1017
1018    if( nb == 16 )
1019    {
1020       uint16_t* im16 = (uint16_t*)im;
1021       switch( swap )
1022       {
1023          case 0:
1024          case 12:
1025          case 1234:
1026             break;
1027          case 21:
1028          case 3412:
1029          case 2143:
1030          case 4321:
1031             for(i=0; i < lgr/2; i++)
1032             {
1033                im16[i]= (im16[i] >> 8) | (im16[i] << 8 );
1034             }
1035             break;
1036          default:
1037             std::cout << "SWAP value (16 bits) not allowed :i" << swap << 
1038             std::endl;
1039       }
1040    }
1041    else if( nb == 32 )
1042    {
1043       uint32_t s32;
1044       uint16_t fort, faible;
1045       uint32_t* im32 = (uint32_t*)im;
1046       switch ( swap )
1047       {
1048          case 0:
1049          case 1234:
1050             break;
1051          case 4321:
1052             for(i = 0; i < lgr/4; i++)
1053             {
1054                faible  = im32[i] & 0x0000ffff;  // 4321
1055                fort    = im32[i] >> 16;
1056                fort    = ( fort >> 8   ) | ( fort << 8 );
1057                faible  = ( faible >> 8 ) | ( faible << 8);
1058                s32     = faible;
1059                im32[i] = ( s32 << 16 ) | fort;
1060             }
1061             break;
1062          case 2143:
1063             for(i = 0; i < lgr/4; i++)
1064             {
1065                faible  = im32[i] & 0x0000ffff;   // 2143
1066                fort    = im32[i] >> 16;
1067                fort    = ( fort >> 8 ) | ( fort << 8 );
1068                faible  = ( faible >> 8) | ( faible << 8);
1069                s32     = fort; 
1070                im32[i] = ( s32 << 16 ) | faible;
1071             }
1072             break;
1073          case 3412:
1074             for(i = 0; i < lgr/4; i++)
1075             {
1076                faible  = im32[i] & 0x0000ffff; // 3412
1077                fort    = im32[i] >> 16;
1078                s32     = faible;
1079                im32[i] = ( s32 << 16 ) | fort;
1080             }
1081             break;
1082          default:
1083             std::cout << "SWAP value (32 bits) not allowed : " << swap << 
1084             std::endl;
1085       }
1086    }
1087 }
1088
1089 /**
1090  * \ingroup gdcmFile
1091  * \brief   Read pixel data from disk (optionaly decompressing) into the
1092  *          caller specified memory location.
1093  * @param   destination where the pixel data should be stored.
1094  *
1095  */
1096 bool gdcmFile::ReadPixelData(void* destination) 
1097 {
1098    FILE* fp = Header->OpenFile();
1099
1100    if ( !fp )
1101    {
1102       return false;
1103    }
1104    if ( fseek(fp, Header->GetPixelOffset(), SEEK_SET) == -1 )
1105    {
1106       Header->CloseFile();
1107       return false;
1108    }
1109
1110    // ----------------------  Compacted File (12 Bits Per Pixel)
1111    // unpack 12 Bits pixels into 16 Bits pixels
1112    // 2 pixels 12bit =     [0xABCDEF]
1113    // 2 pixels 16bit = [0x0ABD] + [0x0FCE]
1114    
1115    if ( Header->GetBitsAllocated() == 12 )
1116    {
1117       int nbPixels = Header->GetXSize() * Header->GetYSize();
1118       uint8_t b0, b1, b2;
1119       
1120       uint16_t* pdestination = (uint16_t*)destination;    
1121       for(int p = 0; p < nbPixels; p += 2 )
1122       {
1123          fread(&b0,1,1,fp);
1124          fread(&b1,1,1,fp);
1125          fread(&b2,1,1,fp);      
1126
1127          //Two steps is necessary to please VC++
1128          *pdestination++ =  ((b0 >> 4) << 8) + ((b0 & 0x0f) << 4) + (b1 & 0x0f);
1129          //                     A                     B                 D
1130          *pdestination++ =  ((b2 & 0x0f) << 8) + ((b1 >> 4) << 4) + (b2 >> 4);
1131          //                     F                     C                 E
1132   
1133          // Troubles expected on Big-Endian processors ?
1134       }
1135
1136       Header->CloseFile();
1137       return true;
1138    }
1139
1140    // ----------------------  Uncompressed File
1141    if ( !Header->IsDicomV3()                             ||
1142         Header->IsImplicitVRLittleEndianTransferSyntax() ||
1143         Header->IsExplicitVRLittleEndianTransferSyntax() ||
1144         Header->IsExplicitVRBigEndianTransferSyntax()    ||
1145         Header->IsDeflatedExplicitVRLittleEndianTransferSyntax() )
1146    {
1147       size_t ItemRead = fread(destination, Header->GetPixelAreaLength(), 1, fp);
1148       Header->CloseFile();
1149       if ( ItemRead != 1 )
1150       {
1151          return false;
1152       }
1153       else
1154       {
1155          return true;
1156       }
1157    }
1158
1159    // ---------------------- Run Length Encoding
1160    if ( Header->IsRLELossLessTransferSyntax() )
1161    {
1162       bool res = gdcm_read_RLE_file (fp,destination);
1163       Header->CloseFile();
1164       return res; 
1165    }  
1166     
1167    // --------------- SingleFrame/Multiframe JPEG Lossless/Lossy/2000 
1168    int nb;
1169    std::string str_nb = Header->GetEntryByNumber(0x0028,0x0100);
1170    if ( str_nb == GDCM_UNFOUND )
1171    {
1172       nb = 16;
1173    }
1174    else
1175    {
1176       nb = atoi( str_nb.c_str() );
1177       if ( nb == 12 )
1178       {
1179          nb = 16;  // ?? 12 should be ACR-NEMA only
1180       }
1181    }
1182
1183    int nBytes= nb/8;
1184    int taille = Header->GetXSize() * Header->GetYSize()  
1185                 * Header->GetSamplesPerPixel();
1186    long fragmentBegining; // for ftell, fseek
1187
1188    bool jpg2000     = Header->IsJPEG2000();
1189    bool jpgLossless = Header->IsJPEGLossless();
1190
1191    bool res = true;
1192    uint16_t ItemTagGr, ItemTagEl;
1193    int ln;  
1194    
1195    //  Position on begining of Jpeg Pixels
1196    
1197    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
1198    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
1199    if(Header->GetSwapCode())
1200    {
1201       ItemTagGr = Header->SwapShort(ItemTagGr);
1202       ItemTagEl = Header->SwapShort(ItemTagEl);
1203    }
1204
1205    fread(&ln,4,1,fp);
1206    if( Header->GetSwapCode() )
1207    {
1208       ln = Header->SwapLong( ln );    // Basic Offset Table Item length
1209    }
1210
1211    if ( ln != 0 )
1212    {
1213       // What is it used for ?!?
1214       uint8_t* BasicOffsetTableItemValue = new uint8_t[ln+1];
1215       fread(BasicOffsetTableItemValue,ln,1,fp);
1216       //delete[] BasicOffsetTableItemValue;
1217    }
1218
1219    // first Fragment initialisation
1220    fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
1221    fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
1222    if( Header->GetSwapCode() )
1223    {
1224       ItemTagGr = Header->SwapShort( ItemTagGr );
1225       ItemTagEl = Header->SwapShort( ItemTagEl );
1226    }
1227
1228    // parsing fragments until Sequence Delim. Tag found
1229    while ( ItemTagGr == 0xfffe && ItemTagEl != 0xe0dd )
1230    {
1231       // --- for each Fragment
1232       fread(&ln,4,1,fp);
1233       if( Header->GetSwapCode() )
1234       {
1235          ln = Header->SwapLong(ln);    // Fragment Item length
1236       }
1237       fragmentBegining = ftell( fp );
1238
1239       if ( jpg2000 )
1240       {
1241       // JPEG 2000 :    call to ???
1242       res = gdcm_read_JPEG2000_file (fp,destination);  // Not Yet written 
1243       // ------------------------------------- endif (JPEG2000)
1244       }
1245       else if (jpgLossless)
1246       {
1247          // JPEG LossLess : call to xmedcom Lossless JPEG
1248          // Reading Fragment pixels
1249          JPEGLosslessDecodeImage (fp, (uint16_t*)destination,
1250                Header->GetPixelSize() * 8 * Header->GetSamplesPerPixel(), ln);
1251          res = 1; // in order not to break the loop
1252   
1253       } // ------------------------------------- endif (JPEGLossless)
1254       else
1255       {
1256          // JPEG Lossy : call to IJG 6b
1257          if ( Header->GetBitsStored() == 8)
1258          {
1259             // Reading Fragment pixels
1260             res = gdcm_read_JPEG_file (fp,destination);
1261          }
1262          else
1263          {
1264             // Reading Fragment pixels
1265             res = gdcm_read_JPEG_file12 (fp,destination);
1266          }
1267          // ------------------------------------- endif (JPEGLossy)
1268       }
1269
1270       if ( !res )
1271       {
1272          break;
1273       }
1274                
1275       // location in user's memory 
1276       // for next fragment (if any) 
1277       destination = (uint8_t*)destination + taille * nBytes;
1278
1279       fseek(fp,fragmentBegining, SEEK_SET); // To be sure we start 
1280       fseek(fp,ln,SEEK_CUR);                // at the begining of next fragment
1281       
1282       ItemTagGr = ItemTagEl = 0;
1283       fread(&ItemTagGr,2,1,fp);  // Reading (fffe) : Item Tag Gr
1284       fread(&ItemTagEl,2,1,fp);  // Reading (e000) : Item Tag El
1285       if( Header->GetSwapCode() )
1286       {
1287          ItemTagGr = Header->SwapShort( ItemTagGr );
1288          ItemTagEl = Header->SwapShort( ItemTagEl );
1289       }
1290    }
1291    // endWhile parsing fragments until Sequence Delim. Tag found    
1292
1293    Header->CloseFile();
1294    return res;
1295 }
1296 //-----------------------------------------------------------------------------