]> Creatis software - gdcm.git/blob - src/gdcmHeader.cxx
Comments added
[gdcm.git] / src / gdcmHeader.cxx
1 // gdcmHeader.cxx
2 //-----------------------------------------------------------------------------
3 #include <stdio.h>
4 #include <cerrno>
5 #include <cctype>    // for isalpha
6 #include <vector>
7
8 #include "gdcmHeader.h"
9 #include "gdcmGlobal.h"
10 #include "gdcmUtil.h"
11 #include "gdcmDebug.h"
12 #include "gdcmTS.h"
13
14 //-----------------------------------------------------------------------------
15 // Constructor / Destructor
16 /**
17  * \brief  Constructor 
18  * @param  InFilename name of the file whose header we want to analyze
19  * @param  exception_on_error whether we want to throw an exception or not
20  * @param  enable_sequences = true to allow the header 
21  *         to be parsed *inside* the SeQuences, when they have an actual length 
22  * @param  ignore_shadow = true if user wants to skip shadow groups 
23  *         during parsing, to save memory space
24  */
25 gdcmHeader::gdcmHeader(const char *InFilename, 
26                        bool exception_on_error,
27                        bool enable_sequences, 
28                        bool ignore_shadow):
29    gdcmParser(InFilename,exception_on_error,enable_sequences,ignore_shadow)
30
31    
32    // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
33    // We may encounter the 'RETired' (0x0028, 0x0200) tag
34    // (Image Location") . This Element contains the number of
35    // the group that contains the pixel data (hence the "Pixel Data"
36    // is found by indirection through the "Image Location").
37    // Inside the group pointed by "Image Location" the searched element
38    // is conventionally the element 0x0010 (when the norm is respected).
39    // When the "Image Location" is absent we default to group 0x7fe0.
40    
41    // This IS the right place for the code
42  
43       std::string ImageLocation = GetEntryByNumber(0x0028, 0x0200);
44       if ( ImageLocation == GDCM_UNFOUND ) { // Image Location
45          GrPixel = 0x7fe0;                   // default value
46       } else {
47          GrPixel = (guint16) atoi( ImageLocation.c_str() );
48       }   
49       if (GrPixel == 0xe07f) // sometimes Image Location value doesn't follow 
50          GrPixel = 0x7fe0;   // the supposed processor endianity. 
51                              // see gdcmData/cr172241.dcm      
52       if (GrPixel != 0x7fe0) 
53          // This is a kludge for old dirty Philips imager.
54          NumPixel = 0x1010;
55       else
56          NumPixel = 0x0010;
57
58       TagKey key = gdcmDictEntry::TranslateToKey(GrPixel, NumPixel);
59       countGrPixel = GetEntry().count(key);
60 }
61
62 /**
63  * \brief Constructor  
64  * @param exception_on_error whether we want to throw an exception or not
65  */
66 gdcmHeader::gdcmHeader(bool exception_on_error) :
67    gdcmParser(exception_on_error)
68 {
69 }
70
71 /**
72  * \ingroup gdcmHeader
73  * \brief   Canonical destructor.
74  */
75 gdcmHeader::~gdcmHeader (void) {
76 }
77
78 //-----------------------------------------------------------------------------
79 // Print
80
81 // see gdcmParser.cxx
82 //-----------------------------------------------------------------------------
83 // Public
84
85 /**
86  * \ingroup gdcmHeader
87  * \brief  This predicate, based on hopefully reasonable heuristics,
88  *         decides whether or not the current gdcmParser was properly parsed
89  *         and contains the mandatory information for being considered as
90  *         a well formed and usable Dicom/Acr File.
91  * @return true when gdcmParser is the one of a reasonable Dicom/Acr file,
92  *         false otherwise. 
93  */
94 bool gdcmHeader::IsReadable(void) {
95    if(!gdcmParser::IsReadable()) {
96       return(false);
97    }
98    std::string res = GetEntryByNumber(0x0028, 0x0005);
99    if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 ) 
100       return false; // Image Dimensions
101    if ( !GetHeaderEntryByNumber(0x0028, 0x0100) )
102       return false; // "Bits Allocated"
103    if ( !GetHeaderEntryByNumber(0x0028, 0x0101) )
104       return false; // "Bits Stored"
105    if ( !GetHeaderEntryByNumber(0x0028, 0x0102) )
106       return false; // "High Bit"
107    if ( !GetHeaderEntryByNumber(0x0028, 0x0103) )
108       return false; // "Pixel Representation" i.e. 'Sign'
109    return true;
110 }
111
112 /**
113  * \ingroup gdcmHeader
114  * \brief   Determines if the Transfer Syntax was already encountered
115  *          and if it corresponds to a JPEGBaseLineProcess1 one.
116  * @return  True when JPEGBaseLineProcess1found. False in all other cases.
117  */
118 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
119    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
120    if ( !Element )
121       return false;
122    LoadHeaderEntrySafe(Element);
123
124    std::string Transfer = Element->GetValue();
125    if ( Transfer == "1.2.840.10008.1.2.4.50" )
126       return true;
127    return false;
128 }
129
130 /**
131  * \ingroup gdcmHeader
132  * \brief   Determines if the Transfer Syntax was already encountered
133  *          and if it corresponds to a JPEGExtendedProcess2-4 one.
134  * @return  True when JPEGExtendedProcess2-4 found. False in all other cases.
135  */
136 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
137    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
138    if ( !Element )
139       return false;
140    LoadHeaderEntrySafe(Element);
141    return ( Element->GetValue() == "1.2.840.10008.1.2.4.51" );
142 }
143
144 /**
145  * \ingroup gdcmHeader
146  * \brief   Determines if the Transfer Syntax was already encountered
147  *          and if it corresponds to a JPEGExtendeProcess3-5 one.
148  * @return  True when JPEGExtendedProcess3-5 found. False in all other cases.
149  */
150 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
151    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
152    if ( !Element )
153       return false;
154    LoadHeaderEntrySafe(Element);
155
156    std::string Transfer = Element->GetValue();
157    if ( Transfer == "1.2.840.10008.1.2.4.52" )
158       return true;
159    return false;
160 }
161
162 /**
163  * \ingroup gdcmHeader
164  * \brief   Determines if the Transfer Syntax was already encountered
165  *          and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
166  * @return  True when JPEGSpectralSelectionProcess6-8 found. False in all
167  *          other cases.
168  */
169 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
170    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
171    if ( !Element )
172       return false;
173    LoadHeaderEntrySafe(Element);
174
175    std::string Transfer = Element->GetValue();
176    if ( Transfer == "1.2.840.10008.1.2.4.53" )
177       return true;
178    return false;
179 }
180
181 /**
182  * \ingroup gdcmHeader
183  * \brief   Determines if the Transfer Syntax was already encountered
184  *          and if it corresponds to a RLE Lossless one.
185  * @return  True when RLE Lossless found. False in all
186  *          other cases.
187  */
188 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
189    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
190    if ( !Element )
191       return false;
192    LoadHeaderEntrySafe(Element);
193
194    std::string Transfer = Element->GetValue();
195    if ( Transfer == "1.2.840.10008.1.2.5" ) {
196       return true;
197     }
198    return false;
199 }
200
201 /**
202  * \ingroup gdcmHeader
203  * \brief  Determines if Transfer Syntax was already encountered
204  *          and if it corresponds to a JPEG Lossless one. 
205  * @return  True when RLE Lossless found. False in all
206  *          other cases. 
207  */
208 bool gdcmHeader::IsJPEGLossless(void) {
209    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
210     // faire qq chose d'intelligent a la place de ça
211    if ( !Element )
212       return false;
213    LoadHeaderEntrySafe(Element);
214
215    const char * Transfert = Element->GetValue().c_str();
216    if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
217    if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
218    if (Element->GetValue() == "1.2.840.10008.1.2.4.57")   return true;
219
220    return false;
221 }
222
223 /**
224  * \ingroup gdcmHeader
225  * \brief   Determines if the Transfer Syntax was already encountered
226  *          and if it corresponds to a JPEG2000 one
227  * @return  True when JPEG2000 (Lossly or LossLess) found. False in all
228  *          other cases.
229  */
230 bool gdcmHeader::IsJPEG2000(void) {
231    gdcmHeaderEntry* Element = GetHeaderEntryByNumber(0x0002, 0x0010);
232    if ( !Element )
233       return false;
234    LoadHeaderEntrySafe(Element);
235
236    std::string Transfer = Element->GetValue();
237    if (    (Transfer == "1.2.840.10008.1.2.4.90") 
238         || (Transfer == "1.2.840.10008.1.2.4.91") )
239       return true;
240    return false;
241 }
242
243 /**
244  * \ingroup gdcmHeader
245  * \brief   Predicate for dicom version 3 file.
246  * @return  True when the file is a dicom version 3.
247  */
248 bool gdcmHeader::IsDicomV3(void) {
249    // Checking if Transfert Syntax exists is enough
250    // Anyway, it's to late check if the 'Preamble' was found ...
251    // And ... would it be a rich idea to check ?
252    // (some 'no Preamble' DICOM images exist !)
253    return (GetHeaderEntryByNumber(0x0002, 0x0010) != NULL);
254 }
255
256 /**
257  * \ingroup gdcmHeader
258  * \brief   Retrieve the number of columns of image.
259  * @return  The encountered size when found, 0 by default.
260  *          0 means the file is NOT USABLE. The caller will have to check
261  */
262 int gdcmHeader::GetXSize(void) {
263    std::string StrSize;
264    StrSize = GetEntryByNumber(0x0028,0x0011);
265    if (StrSize == GDCM_UNFOUND)
266       return 0;
267    return atoi(StrSize.c_str());
268 }
269
270 /**
271  * \ingroup gdcmHeader
272  * \brief   Retrieve the number of lines of image.
273  * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
274  * @return  The encountered size when found, 1 by default 
275  *          (The ACR-MEMA file contains a Signal, not an Image).
276  */
277 int gdcmHeader::GetYSize(void) {
278    std::string StrSize = GetEntryByNumber(0x0028,0x0010);
279    if (StrSize != GDCM_UNFOUND)
280       return atoi(StrSize.c_str());
281    if ( IsDicomV3() )
282       return 0;
283    else
284       // The Rows (0028,0010) entry was optional for ACR/NEMA. It might
285       // hence be a signal (1d image). So we default to 1:
286       return 1;
287 }
288
289 /**
290  * \ingroup gdcmHeader
291  * \brief   Retrieve the number of planes of volume or the number
292  *          of frames of a multiframe.
293  * \warning When present we consider the "Number of Frames" as the third
294  *          dimension. When absent we consider the third dimension as
295  *          being the ACR-NEMA "Planes" tag content.
296  * @return  The encountered size when found, 1 by default (single image).
297  */
298 int gdcmHeader::GetZSize(void) {
299    // Both  DicomV3 and ACR/Nema consider the "Number of Frames"
300    // as the third dimension.
301    std::string StrSize = GetEntryByNumber(0x0028,0x0008);
302    if (StrSize != GDCM_UNFOUND)
303       return atoi(StrSize.c_str());
304
305    // We then consider the "Planes" entry as the third dimension 
306    StrSize = GetEntryByNumber(0x0028,0x0012);
307    if (StrSize != GDCM_UNFOUND)
308       return atoi(StrSize.c_str());
309    return 1;
310 }
311
312 /**
313  * \ingroup gdcmHeader
314  * \brief   Retrieve the number of Bits Stored (actually used)
315  *          (as opposite to number of Bits Allocated)
316  * @return  The encountered number of Bits Stored, 0 by default.
317  *          0 means the file is NOT USABLE. The caller has to check it !
318  */
319 int gdcmHeader::GetBitsStored(void) {  
320    std::string StrSize = GetEntryByNumber(0x0028,0x0101);
321    if (StrSize == GDCM_UNFOUND)
322       return 0;  // It's supposed to be mandatory
323                  // the caller will have to check
324    return atoi(StrSize.c_str());
325 }
326
327 /**
328  * \ingroup gdcmHeader
329  * \brief   Retrieve the number of Bits Allocated
330  *          (8, 12 -compacted ACR-NEMA files, 16, ...)
331  * @return  The encountered number of Bits Allocated, 0 by default.
332  *          0 means the file is NOT USABLE. The caller has to check it !
333  */
334 int gdcmHeader::GetBitsAllocated(void) {
335    std::string StrSize = GetEntryByNumber(0x0028,0x0100);
336    if (StrSize == GDCM_UNFOUND)
337       return 0; // It's supposed to be mandatory
338                 // the caller will have to check
339    return atoi(StrSize.c_str());
340 }
341
342 /**
343  * \ingroup gdcmHeader
344  * \brief   Retrieve the number of Samples Per Pixel
345  *          (1 : gray level, 3 : RGB -1 or 3 Planes-)
346  * @return  The encountered number of Samples Per Pixel, 1 by default.
347  *          (Gray level Pixels)
348  */
349 int gdcmHeader::GetSamplesPerPixel(void) {
350    std::string StrSize = GetEntryByNumber(0x0028,0x0002);
351    if (StrSize == GDCM_UNFOUND)
352       return 1; // Well, it's supposed to be mandatory ...
353                 // but sometimes it's missing : *we* assume Gray pixels
354    return atoi(StrSize.c_str());
355 }
356
357 /**
358  * \ingroup gdcmHeader
359  * \brief   Retrieve the Planar Configuration for RGB images
360  *          (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
361  * @return  The encountered Planar Configuration, 0 by default.
362  */
363 int gdcmHeader::GetPlanarConfiguration(void) {
364    std::string StrSize = GetEntryByNumber(0x0028,0x0006);
365    if (StrSize == GDCM_UNFOUND)
366       return 0;
367    return atoi(StrSize.c_str());
368 }
369
370 /**
371  * \ingroup gdcmHeader
372  * \brief   Return the size (in bytes) of a single pixel of data.
373  * @return  The size in bytes of a single pixel of data; 0 by default
374  *          0 means the file is NOT USABLE; the caller will have to check        
375  */
376 int gdcmHeader::GetPixelSize(void) {
377    std::string PixelType = GetPixelType();
378    if (PixelType == "8U"  || PixelType == "8S")
379       return 1;
380    if (PixelType == "16U" || PixelType == "16S")
381       return 2;
382    if (PixelType == "32U" || PixelType == "32S")
383       return 4;
384    if (PixelType == "FD")
385       return 8;         
386    dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
387    return 0;
388 }
389
390 /**
391  * \ingroup gdcmHeader
392  * \brief   Build the Pixel Type of the image.
393  *          Possible values are:
394  *          - 8U  unsigned  8 bit,
395  *          - 8S    signed  8 bit,
396  *          - 16U unsigned 16 bit,
397  *          - 16S   signed 16 bit,
398  *          - 32U unsigned 32 bit,
399  *          - 32S   signed 32 bit,
400  *          - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
401  * \warning 12 bit images appear as 16 bit.
402  *          24 bit images appear as 8 bit
403  * @return  0S if nothing found. NOT USABLE file. The caller has to check
404  */
405 std::string gdcmHeader::GetPixelType(void) { 
406    std::string BitsAlloc = GetEntryByNumber(0x0028, 0x0100); // Bits Allocated
407    if (BitsAlloc == GDCM_UNFOUND) {
408       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
409       BitsAlloc = std::string("16");
410    }
411    if (BitsAlloc == "64")            // )
412       return ("FD");
413    if (BitsAlloc == "12")            // It will be unpacked
414       BitsAlloc = std::string("16");
415    else if (BitsAlloc == "24")       // (in order no to be messed up
416       BitsAlloc = std::string("8");  // by old RGB images)
417      
418    std::string Signed = GetEntryByNumber(0x0028, 0x0103); // "Pixel Representation"
419    if (Signed == GDCM_UNFOUND) {
420       dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
421       BitsAlloc = std::string("0");
422    }
423    if (Signed == "0")
424       Signed = std::string("U");
425    else
426       Signed = std::string("S");
427
428    return( BitsAlloc + Signed);
429 }
430
431
432 /**
433  * \ingroup gdcmHeader
434  * \brief   Recover the offset (from the beginning of the file) 
435  *          of *image* pixels (not *icone image* pixels, if any !)
436  * @return Pixel Offset
437  */
438 size_t gdcmHeader::GetPixelOffset(void) { 
439    //
440    // If the element (0x0088,0x0200) 'icone image sequence' is found
441    // (grPixel,numPixel) is stored twice : the first one for the icon
442    // the second one for the image ...
443    // pb : sometimes , (0x0088,0x0200) exists, but doesn't contain *anything*
444    // see gdcmData/MxTwinLossLess.dcm ...
445
446    //std::string icone = GetEntryByNumber(0x0088,0x0200); //icone image sequence
447       
448    IterHT it = GetHeaderEntrySameNumber(GrPixel,NumPixel);          
449    TagKey key = gdcmDictEntry::TranslateToKey(GrPixel,NumPixel);
450    gdcmHeaderEntry* PixelElement;
451    if (countGrPixel == 1)   
452       PixelElement = (it.first)->second;
453    else {
454       PixelElement = (++it.first)->second; // hope there are no more than 2 !
455    } 
456    if (PixelElement) {
457       return PixelElement->GetOffset();
458    } else {
459 /*      std::cout << "Big trouble : Pixel Element ("
460                 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found"
461                 << std::endl;  */
462       return 0;
463    }     
464 }
465 // TODO : unify those two (previous one and next one)
466 /**
467  * \ingroup gdcmHeader
468  * \brief   Recover the pixel area length (in Bytes)
469  * @return Pixel Element Length, as stored in the header
470  *         (NOT the memory space necessary to hold the Pixels 
471  *          -in case of embeded compressed image-)
472  *         0 : NOT USABLE file. The caller has to check.
473  */
474 size_t gdcmHeader::GetPixelAreaLength(void) { 
475           
476    IterHT it = GetHeaderEntrySameNumber(GrPixel,NumPixel);          
477    TagKey key = gdcmDictEntry::TranslateToKey(GrPixel,NumPixel);
478    gdcmHeaderEntry* PixelElement;
479   
480   if (countGrPixel==1)  
481       PixelElement = (it.first)->second;
482    else
483       PixelElement = (++it.first)->second;
484
485    if (PixelElement) {
486       return PixelElement->GetLength();
487    } else {
488 /*      std::cout << "Big trouble : Pixel Element ("
489                 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found"
490                 << std::endl;
491 */
492       return 0;
493    }
494 }
495
496 /**
497   * \ingroup gdcmHeader
498   * \brief tells us if LUT are used
499   * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
500   *          are NOT considered as LUT, since nobody knows
501   *          how to deal with them
502   *          Please warn me if you know sbdy that *does* know ... jprx
503   * @return true if LUT Descriptors and LUT Tables were found 
504   */
505 bool gdcmHeader::HasLUT(void) {
506
507    // Check the presence of the LUT Descriptors, and LUT Tables    
508    // LutDescriptorRed    
509    if ( !GetHeaderEntryByNumber(0x0028,0x1101) )
510       return false;
511    // LutDescriptorGreen 
512    if ( !GetHeaderEntryByNumber(0x0028,0x1102) )
513       return false;
514    // LutDescriptorBlue 
515    if ( !GetHeaderEntryByNumber(0x0028,0x1103) )
516       return false;   
517    // Red Palette Color Lookup Table Data
518    if ( !GetHeaderEntryByNumber(0x0028,0x1201) )
519       return false; 
520    // Green Palette Color Lookup Table Data       
521    if ( !GetHeaderEntryByNumber(0x0028,0x1202) )
522       return false;
523    // Blue Palette Color Lookup Table Data      
524    if ( !GetHeaderEntryByNumber(0x0028,0x1203) )
525       return false;
526    // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
527    //         NOT taken into account, but we don't know how to use it ...   
528    return true;
529 }
530
531 /**
532   * \ingroup gdcmHeader
533   * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
534   *             else 0
535   * @return Lookup Table number of Bits , 0 by default
536   *          when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
537   * @ return bit number of each LUT item 
538   */
539 int gdcmHeader::GetLUTNbits(void) {
540    std::vector<std::string> tokens;
541    //int LutLength;
542    //int LutDepth;
543    int LutNbits;
544    //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
545    // Consistency already checked in GetLUTLength
546    std::string LutDescription = GetEntryByNumber(0x0028,0x1101);
547    if (LutDescription == GDCM_UNFOUND)
548       return 0;
549    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
550    Tokenize (LutDescription, tokens, "\\");
551    //LutLength=atoi(tokens[0].c_str());
552    //LutDepth=atoi(tokens[1].c_str());
553    LutNbits=atoi(tokens[2].c_str());
554    tokens.clear();
555    return LutNbits;
556 }
557
558 /**
559   * \ingroup gdcmHeader
560   * \brief builts Red/Green/Blue/Alpha LUT from Header
561   *         when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
562   *          and (0028,1101),(0028,1102),(0028,1102)  
563   *            - xxx Palette Color Lookup Table Descriptor - are found
564   *          and (0028,1201),(0028,1202),(0028,1202) 
565   *            - xxx Palette Color Lookup Table Data - are found 
566   * \warning does NOT deal with :
567   *   0028 1100 Gray Lookup Table Descriptor (Retired)
568   *   0028 1221 Segmented Red Palette Color Lookup Table Data
569   *   0028 1222 Segmented Green Palette Color Lookup Table Data
570   *   0028 1223 Segmented Blue Palette Color Lookup Table Data 
571   *   no known Dicom reader deals with them :-(
572   * @return a RGBA Lookup Table 
573   */ 
574 unsigned char * gdcmHeader::GetLUTRGBA(void) {
575 // Not so easy : see 
576 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
577
578 //  if Photometric Interpretation # PALETTE COLOR, no LUT to be done
579    if (GetEntryByNumber(0x0028,0x0004) != "PALETTE COLOR ") {
580       return NULL;
581    }  
582    int lengthR, debR, nbitsR;
583    int lengthG, debG, nbitsG;
584    int lengthB, debB, nbitsB;
585    
586 // Get info from Lut Descriptors
587 // (the 3 LUT descriptors may be different)    
588    std::string LutDescriptionR = GetEntryByNumber(0x0028,0x1101);
589    if (LutDescriptionR == GDCM_UNFOUND)
590       return NULL;
591    std::string LutDescriptionG = GetEntryByNumber(0x0028,0x1102);
592    if (LutDescriptionG == GDCM_UNFOUND)
593       return NULL;   
594    std::string LutDescriptionB = GetEntryByNumber(0x0028,0x1103);
595    if (LutDescriptionB == GDCM_UNFOUND)
596       return NULL;
597       
598    std::vector<std::string> tokens;
599       
600    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
601    Tokenize (LutDescriptionR, tokens, "\\");
602    lengthR=atoi(tokens[0].c_str()); // Red LUT length in Bytes
603    debR   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
604    nbitsR =atoi(tokens[2].c_str()); // Lut item size (in Bits)
605    tokens.clear();
606    
607    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
608    Tokenize (LutDescriptionG, tokens, "\\");
609    lengthG=atoi(tokens[0].c_str()); // Green LUT length in Bytes
610    debG   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
611    nbitsG =atoi(tokens[2].c_str()); // Lut item size (in Bits)
612    tokens.clear();  
613    
614    tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
615    Tokenize (LutDescriptionB, tokens, "\\");
616    lengthB=atoi(tokens[0].c_str()); // Blue LUT length in Bytes
617    debB   =atoi(tokens[1].c_str()); // subscript of the first Lut Value
618    nbitsB =atoi(tokens[2].c_str()); // Lut item size (in Bits)
619    tokens.clear();
620  
621    // Load LUTs into memory, (as they were stored on disk)
622    unsigned char *lutR = (unsigned char *)
623                          GetEntryVoidAreaByNumber(0x0028,0x1201);
624    unsigned char *lutG = (unsigned char *)
625                          GetEntryVoidAreaByNumber(0x0028,0x1202);
626    unsigned char *lutB = (unsigned char *)
627                          GetEntryVoidAreaByNumber(0x0028,0x1203); 
628    
629    if (!lutR || !lutG || !lutB ) {
630       return NULL;
631    } 
632    // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT 
633    
634    unsigned char *LUTRGBA = (unsigned char *)calloc(1024,1); // 256 * 4 (R, G, B, Alpha) 
635    if (!LUTRGBA) {
636       return NULL;
637    }
638    memset(LUTRGBA, 0, 1024);
639    // Bits Allocated
640    int nb;
641    std::string str_nb = GetEntryByNumber(0x0028,0x0100);
642    if (str_nb == GDCM_UNFOUND ) {
643       nb = 16;
644    } else {
645       nb = atoi(str_nb.c_str() );
646    }  
647    int mult;
648
649    if (nbitsR==16 && nb==8) // when LUT item size is different than pixel size
650       mult=2;               // high byte must be = low byte 
651    else                     // See PS 3.3-2003 C.11.1.1.2 p 619
652       mult=1; 
653  
654    // if we get a black image, let's just remove the '+1'
655    // from 'i*mult+1' and check again 
656    // if it works, we shall have to check the 3 Palettes
657    // to see which byte is ==0 (first one, or second one)
658    // and fix the code
659    // We give up the checking to avoid some (useless ?)overhead 
660    // (optimistic asumption)
661    unsigned char *a;      
662    int i;
663
664    a = LUTRGBA+0;
665    for(i=0;i<lengthR;i++) {
666       *a = lutR[i*mult+1]; 
667       a+=4;       
668    }        
669    a = LUTRGBA+1;
670    for(i=0;i<lengthG;i++) {
671       *a = lutG[i*mult+1]; 
672       a+=4;       
673    }  
674    a = LUTRGBA+2;
675    for(i=0;i<lengthB;i++) {
676       *a = lutB[i*mult+1]; 
677       a+=4;       
678    }  
679    a = LUTRGBA+3;
680    for(i=0;i<256;i++) {
681       *a = 1; // Alpha component
682       a+=4; 
683    } 
684    
685    //How to free the now useless LUTs?
686    //free(LutR); free(LutB); free(LutG); // Seg Fault when used
687    return(LUTRGBA);   
688
689
690 /**
691  * \ingroup gdcmHeader
692  * \brief gets the info from 0002,0010 : Transfert Syntax and gdcmTS
693  *        else 1.
694  * @return the full Transfert Syntax Name (as oposite to Transfert Syntax UID)
695  */
696 std::string gdcmHeader::GetTransfertSyntaxName(void) { 
697    // use the gdcmTS (TS : Transfert Syntax)
698    std::string TransfertSyntax = GetEntryByNumber(0x0002,0x0010);
699    if (TransfertSyntax == GDCM_UNFOUND) {
700       dbg.Verbose(0, "gdcmHeader::GetTransfertSyntaxName: unfound Transfert Syntax (0002,0010)");
701       return "Uncompressed ACR-NEMA";
702    }
703    // we do it only when we need it
704    gdcmTS * ts = gdcmGlobal::GetTS();
705    std::string tsName=ts->GetValue(TransfertSyntax);
706    //delete ts; // Seg Fault when deleted ?!
707    return tsName;
708 }
709
710 /**
711  * \ingroup   gdcmHeader
712  * \brief Sets the Pixel Area size in the Header
713  *        --> not-for-rats function
714  * @param ImageDataSize new Pixel Area Size
715  *        warning : nothing else is checked
716  */
717 void gdcmHeader::SetImageDataSize(size_t ImageDataSize) {
718    std::string content1;
719    char car[20];
720
721    // Assumes HeaderEntry (GrPixel, NumPixel) is unique ...   
722    // TODO deal with multiplicity (see gdcmData/icone.dcm)
723    sprintf(car,"%d",ImageDataSize);
724  
725    gdcmHeaderEntry *a = GetHeaderEntryByNumber(GrPixel, NumPixel);
726    a->SetLength(ImageDataSize);
727
728    ImageDataSize+=8;
729    sprintf(car,"%d",ImageDataSize);
730    content1=car;
731    SetEntryByNumber(content1, GrPixel, NumPixel);
732 }
733
734
735 /**
736  * \ingroup   gdcmHeader
737  * \brief compares 2 Headers, according to DICOMDIR rules
738  *        --> not-for-rats function
739  * \warning does NOT work with ACR-NEMA files
740  * \todo find a trick to solve the pb (use RET fields ?)
741  * @param header 
742  * @return true if 'smaller'
743  */
744  bool gdcmHeader::operator<(gdcmHeader &header){
745    std::string s1,s2;
746
747    // Patient Name
748    s1=this->GetEntryByNumber(0x0010,0x0010);
749    s2=header.GetEntryByNumber(0x0010,0x0010);
750    if(s1 < s2)
751       return(true);
752    else if(s1 > s2)
753       return(false);
754    else
755    {
756       // Patient ID
757       s1=this->GetEntryByNumber(0x0010,0x0020);
758       s2=header.GetEntryByNumber(0x0010,0x0020);
759       if (s1 < s2)
760          return(true);
761       else if (s1 > s2)
762          return(1);
763       else
764       {
765          // Study Instance UID
766          s1=this->GetEntryByNumber(0x0020,0x000d);
767          s2=header.GetEntryByNumber(0x0020,0x000d);
768          if (s1 < s2)
769             return(true);
770          else if(s1 > s2)
771             return(false);
772          else
773          {
774             // Serie Instance UID
775             s1=this->GetEntryByNumber(0x0020,0x000e);
776             s2=header.GetEntryByNumber(0x0020,0x000e);
777             if (s1 < s2)
778                return(true);
779             else if(s1 > s2)
780                return(false);
781          }
782       }
783    }
784    return(false);
785 }
786
787 bool gdcmHeader::WriteEntry(gdcmHeaderEntry *tag, FILE *_fp,FileType type)
788 {
789    guint32 length = tag->GetLength();
790                                                                                 
791    // The value of a tag MUST (see the DICOM norm) be an odd number of
792    // bytes. When this is not the case, pad with an additional byte:
793    if(length%2==1)
794    {
795       tag->SetValue(tag->GetValue()+"\0");
796       tag->SetLength(tag->GetReadLength()+1);
797    }
798                                                                                 
799    WriteEntryTagVRLength(tag, _fp, type);
800                                                                                 
801    // Pixels are never loaded in the element !
802    // we stop writting when Pixel are processed
803    // FIX : we loose trailing elements (RAB, right now)
804    guint16 el     = tag->GetElement();
805    guint16 group  = tag->GetGroup();
806    int compte =0;
807    if ((group == GrPixel) && (el == NumPixel) ) {
808       compte++;
809       if (compte == countGrPixel) {// we passed *all* the GrPixel,NumPixel
810          return false;
811       }
812    }
813    WriteEntryValue(tag, _fp, type);
814    return true;
815 }
816
817 //-----------------------------------------------------------------------------
818 // Protected
819
820 /**
821  * \ingroup   gdcmHeader
822  * \brief anonymize a Header (removes Patient's personal info)
823  *        (read the code to see which ones ...)
824  */
825 bool gdcmHeader::anonymizeHeader() {
826
827   gdcmHeaderEntry *patientNameHE = GetHeaderEntryByNumber (0x0010, 0x0010);
828  // gdcmHeaderEntry *patientIDHE   = GetHeaderEntryByNumber (0x0010, 0x0020); 
829     
830   ReplaceIfExistByNumber ("  ",0x0010, 0x2154); // Telephone   
831   ReplaceIfExistByNumber ("  ",0x0010, 0x1040); // Adress
832   ReplaceIfExistByNumber ("  ",0x0010, 0x0020); // Patient ID
833   
834   if (patientNameHE) {
835      std::string StudyInstanceUID =  GetEntryByNumber (0x0020, 0x000d);
836      if (StudyInstanceUID !=GDCM_UNFOUND)
837         ReplaceOrCreateByNumber(StudyInstanceUID, 0x0010, 0x0010);
838      else
839         ReplaceOrCreateByNumber(std::string("anonymised"), 0x0010, 0x0010);
840   }
841   
842   // Just for fun :-(
843   // (if any) remove or replace all the stuff that contains a Date
844   
845 //0008 0012 DA ID Instance Creation Date
846 //0008 0020 DA ID Study Date
847 //0008 0021 DA ID Series Date
848 //0008 0022 DA ID Acquisition Date
849 //0008 0023 DA ID Content Date
850 //0008 0024 DA ID Overlay Date
851 //0008 0025 DA ID Curve Date
852 //0008 002a DT ID Acquisition Datetime
853 //0018 9074 DT ACQ Frame Acquisition Datetime
854 //0018 9151 DT ACQ Frame Reference Datetime
855 //0018 a002 DT ACQ Contribution Date Time
856 //0020 3403 SH REL Modified Image Date (RET)
857 //0032 0032 DA SDY Study Verified Date
858 //0032 0034 DA SDY Study Read Date
859 //0032 1000 DA SDY Scheduled Study Start Date
860 //0032 1010 DA SDY Scheduled Study Stop Date
861 //0032 1040 DA SDY Study Arrival Date
862 //0032 1050 DA SDY Study Completion Date
863 //0038 001a DA VIS Scheduled Admission Date
864 //0038 001c DA VIS Scheduled Discharge Date
865 //0038 0020 DA VIS Admitting Date
866 //0038 0030 DA VIS Discharge Date
867 //0040 0002 DA PRC Scheduled Procedure Step Start Date
868 //0040 0004 DA PRC Scheduled Procedure Step End Date
869 //0040 0244 DA PRC Performed Procedure Step Start Date
870 //0040 0250 DA PRC Performed Procedure Step End Date
871 //0040 2004 DA PRC Issue Date of Imaging Service Request
872 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
873 //0040 4011 DT PRC Expected Completion Date and Time
874 //0040 a030 DT PRC Verification Date Time
875 //0040 a032 DT PRC Observation Date Time
876 //0040 a120 DT PRC DateTime
877 //0040 a121 DA PRC Date
878 //0040 a13a DT PRC Referenced Datetime
879 //0070 0082 DA ??? Presentation Creation Date
880 //0100 0420 DT ??? SOP Autorization Date and Time
881 //0400 0105 DT ??? Digital Signature DateTime
882 //2100 0040 DA PJ Creation Date
883 //3006 0008 DA SSET Structure Set Date
884 //3008 0024 DA ??? Treatment Control Point Date
885 //3008 0054 DA ??? First Treatment Date
886 //3008 0056 DA ??? Most Recent Treatment Date
887 //3008 0162 DA ??? Safe Position Exit Date
888 //3008 0166 DA ??? Safe Position Return Date
889 //3008 0250 DA ??? Treatment Date
890 //300a 0006 DA RT RT Plan Date
891 //300a 022c DA RT Air Kerma Rate Reference Date
892 //300e 0004 DA RT Review Date
893  return true;  
894 }
895 //-----------------------------------------------------------------------------
896 // Private
897
898 //-----------------------------------------------------------------------------