1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.69 2003/06/17 17:44:48 jpr Exp $
9 #include <netinet/in.h>
11 #include <cctype> // for isalpha
14 #include "gdcmHeader.h"
18 // TODO : remove DEBUG
21 // Refer to gdcmHeader::CheckSwap()
22 #define HEADER_LENGTH_TO_READ 256
23 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
24 #define _MaxSizeLoadElementValue_ 1024
26 void gdcmHeader::Initialise(void) {
27 dicom_vr = gdcmGlobal::GetVR();
28 dicom_ts = gdcmGlobal::GetTS();
29 Dicts = gdcmGlobal::GetDicts();
30 RefPubDict = Dicts->GetDefaultPubDict();
31 RefShaDict = (gdcmDict*)0;
34 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) {
35 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
36 filename = InFilename;
38 if ( !OpenFile(exception_on_error))
45 gdcmHeader::gdcmHeader(bool exception_on_error) {
46 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
50 bool gdcmHeader::OpenFile(bool exception_on_error)
51 throw(gdcmFileError) {
52 fp=fopen(filename.c_str(),"rb");
53 if(exception_on_error) {
55 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
59 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
63 bool gdcmHeader::CloseFile(void) {
64 int closed = fclose(fp);
71 gdcmHeader::~gdcmHeader (void) {
72 dicom_vr = (gdcmVR*)0;
73 Dicts = (gdcmDictSet*)0;
74 RefPubDict = (gdcmDict*)0;
75 RefShaDict = (gdcmDict*)0;
81 // META Meta Information
93 // NMI Nuclear Medicine
95 // BFS Basic Film Session
97 // BIB Basic Image Box
112 * \ingroup gdcmHeader
113 * \brief Discover what the swap code is (among little endian, big endian,
114 * bad little endian, bad big endian).
117 void gdcmHeader::CheckSwap()
119 // The only guaranted way of finding the swap code is to find a
120 // group tag since we know it's length has to be of four bytes i.e.
121 // 0x00000004. Finding the swap code in then straigthforward. Trouble
122 // occurs when we can't find such group...
124 guint32 x=4; // x : pour ntohs
125 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
129 char deb[HEADER_LENGTH_TO_READ];
131 // First, compare HostByteOrder and NetworkByteOrder in order to
132 // determine if we shall need to swap bytes (i.e. the Endian type).
138 // The easiest case is the one of a DICOM header, since it possesses a
139 // file preamble where it suffice to look for the string "DICM".
140 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
143 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
144 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
145 // Next, determine the value representation (VR). Let's skip to the
146 // first element (0002, 0000) and check there if we find "UL"
147 // - or "OB" if the 1st one is (0002,0001) -,
148 // in which case we (almost) know it is explicit VR.
149 // WARNING: if it happens to be implicit VR then what we will read
150 // is the length of the group. If this ascii representation of this
151 // length happens to be "UL" then we shall believe it is explicit VR.
152 // FIXME: in order to fix the above warning, we could read the next
153 // element value (or a couple of elements values) in order to make
154 // sure we are not commiting a big mistake.
156 // * the 128 bytes of File Preamble (often padded with zeroes),
157 // * the 4 bytes of "DICM" string,
158 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
159 // i.e. a total of 136 bytes.
162 // Use gdcmHeader::dicom_vr to test all the possibilities
163 // instead of just checking for UL, OB and UI !?
164 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
165 (memcmp(entCur, "OB", (size_t)2) == 0) ||
166 (memcmp(entCur, "UI", (size_t)2) == 0) )
168 filetype = ExplicitVR;
169 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
170 "explicit Value Representation");
172 filetype = ImplicitVR;
173 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
174 "not an explicit Value Representation");
179 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
180 "HostByteOrder != NetworkByteOrder");
183 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
184 "HostByteOrder = NetworkByteOrder");
187 // Position the file position indicator at first tag (i.e.
188 // after the file preamble and the "DICM" string).
190 fseek (fp, 132L, SEEK_SET);
194 // Alas, this is not a DicomV3 file and whatever happens there is no file
195 // preamble. We can reset the file position indicator to where the data
196 // is (i.e. the beginning of the file).
197 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
200 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
201 // By clean we mean that the length of the first tag is written down.
202 // If this is the case and since the length of the first group HAS to be
203 // four (bytes), then determining the proper swap code is straightforward.
206 // We assume the array of char we are considering contains the binary
207 // representation of a 32 bits integer. Hence the following dirty
209 s = *((guint32 *)(entCur));
229 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
230 "ACR/NEMA unfound swap info (time to raise bets)");
233 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
234 // It is time for despaired wild guesses. So, let's assume this file
235 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
236 // not present. Then the only info we have is the net2host one.
245 void gdcmHeader::SwitchSwapToBigEndian(void) {
246 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
247 "Switching to BigEndian mode.");
265 * \ingroup gdcmHeader
266 * \brief Find the value representation of the current tag.
268 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
269 if (filetype != ExplicitVR)
275 char msg[100]; // for sprintf. Sorry
277 long PositionOnEntry = ftell(fp);
278 // Warning: we believe this is explicit VR (Value Representation) because
279 // we used a heuristic that found "UL" in the first tag. Alas this
280 // doesn't guarantee that all the tags will be in explicit VR. In some
281 // cases (see e-film filtered files) one finds implicit VR tags mixed
282 // within an explicit VR file. Hence we make sure the present tag
283 // is in explicit VR and try to fix things if it happens not to be
285 bool RealExplicit = true;
287 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
291 // Assume we are reading a falsely explicit VR file i.e. we reached
292 // a tag where we expect reading a VR but are in fact we read the
293 // first to bytes of the length. Then we will interogate (through find)
294 // the dicom_vr dictionary with oddities like "\004\0" which crashes
295 // both GCC and VC++ implementations of the STL map. Hence when the
296 // expected VR read happens to be non-ascii characters we consider
297 // we hit falsely explicit VR tag.
299 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
300 RealExplicit = false;
302 // CLEANME searching the dicom_vr at each occurence is expensive.
303 // PostPone this test in an optional integrity check at the end
304 // of parsing or only in debug mode.
305 if ( RealExplicit && !dicom_vr->Count(vr) )
308 if ( RealExplicit ) {
309 if ( ElVal->IsVrUnknown() ) {
310 // When not a dictionary entry, we can safely overwrite the vr.
314 if ( ElVal->GetVR() == vr ) {
315 // The vr we just read and the dictionary agree. Nothing to do.
318 // The vr present in the file and the dictionary disagree. We assume
319 // the file writer knew best and use the vr of the file. Since it would
320 // be unwise to overwrite the vr of a dictionary (since it would
321 // compromise it's next user), we need to clone the actual DictEntry
322 // and change the vr for the read one.
323 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
328 ElVal->SetDictEntry(NewTag);
332 // We thought this was explicit VR, but we end up with an
333 // implicit VR tag. Let's backtrack.
335 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", ElVal->GetGroup(),ElVal->GetElement());
336 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
338 fseek(fp, PositionOnEntry, SEEK_SET);
339 // When this element is known in the dictionary we shall use, e.g. for
340 // the semantics (see the usage of IsAnInteger), the vr proposed by the
341 // dictionary entry. Still we have to flag the element as implicit since
342 // we know now our assumption on expliciteness is not furfilled.
344 if ( ElVal->IsVrUnknown() )
345 ElVal->SetVR("Implicit");
346 ElVal->SetImplicitVr();
350 * \ingroup gdcmHeader
351 * \brief Determines if the Transfer Syntax was allready encountered
352 * and if it corresponds to a ImplicitVRLittleEndian one.
354 * @return True when ImplicitVRLittleEndian found. False in all other cases.
356 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
357 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
360 LoadElementValueSafe(Element);
361 string Transfer = Element->GetValue();
362 if ( Transfer == "1.2.840.10008.1.2" )
368 * \ingroup gdcmHeader
369 * \brief Determines if the Transfer Syntax was allready encountered
370 * and if it corresponds to a ExplicitVRLittleEndian one.
372 * @return True when ExplicitVRLittleEndian found. False in all other cases.
374 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
375 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
378 LoadElementValueSafe(Element);
379 string Transfer = Element->GetValue();
380 if ( Transfer == "1.2.840.10008.1.2.1" )
386 * \ingroup gdcmHeader
387 * \brief Determines if the Transfer Syntax was allready encountered
388 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
390 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
392 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
393 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
396 LoadElementValueSafe(Element);
397 string Transfer = Element->GetValue();
398 if ( Transfer == "1.2.840.10008.1.2.1.99" )
404 * \ingroup gdcmHeader
405 * \brief Determines if the Transfer Syntax was allready encountered
406 * and if it corresponds to a Explicit VR Big Endian one.
408 * @return True when big endian found. False in all other cases.
410 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
411 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
414 LoadElementValueSafe(Element);
415 string Transfer = Element->GetValue();
416 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
422 * \ingroup gdcmHeader
423 * \brief Determines if the Transfer Syntax was allready encountered
424 * and if it corresponds to a JPEGBaseLineProcess1 one.
426 * @return True when JPEGBaseLineProcess1found. False in all other cases.
428 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
429 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
432 LoadElementValueSafe(Element);
433 string Transfer = Element->GetValue();
434 if ( Transfer == "1.2.840.10008.1.2.4.50" )
440 * \ingroup gdcmHeader
445 bool gdcmHeader::IsJPEGLossless(void) {
446 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
447 // faire qq chose d'intelligent a la place de ça
450 LoadElementValueSafe(Element);
451 const char * Transfert = Element->GetValue().c_str();
452 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
453 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
459 * \ingroup gdcmHeader
460 * \brief Determines if the Transfer Syntax was allready encountered
461 * and if it corresponds to a JPEGExtendedProcess2-4 one.
463 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
465 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
466 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
469 LoadElementValueSafe(Element);
470 string Transfer = Element->GetValue();
471 if ( Transfer == "1.2.840.10008.1.2.4.51" )
477 * \ingroup gdcmHeader
478 * \brief Determines if the Transfer Syntax was allready encountered
479 * and if it corresponds to a JPEGExtendeProcess3-5 one.
481 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
483 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
484 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
487 LoadElementValueSafe(Element);
488 string Transfer = Element->GetValue();
489 if ( Transfer == "1.2.840.10008.1.2.4.52" )
495 * \ingroup gdcmHeader
496 * \brief Determines if the Transfer Syntax was allready encountered
497 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
499 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
502 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
503 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
506 LoadElementValueSafe(Element);
507 string Transfer = Element->GetValue();
508 if ( Transfer == "1.2.840.10008.1.2.4.53" )
514 * \ingroup gdcmHeader
515 * \brief Predicate for dicom version 3 file.
516 * @return True when the file is a dicom version 3.
518 bool gdcmHeader::IsDicomV3(void) {
519 if ( (filetype == ExplicitVR)
520 || (filetype == ImplicitVR) )
526 * \ingroup gdcmHeader
527 * \brief When the length of an element value is obviously wrong (because
528 * the parser went Jabberwocky) one can hope improving things by
529 * applying this heuristic.
531 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
532 if ( FoundLength == 0xffffffff)
534 ElVal->SetLength(FoundLength);
538 * \ingroup gdcmHeader
543 guint32 gdcmHeader::FindLengthOB(void) {
544 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
547 long PositionOnEntry = ftell(fp);
548 bool FoundSequenceDelimiter = false;
549 guint32 TotalLength = 0;
552 while ( ! FoundSequenceDelimiter) {
556 if (DEBUG) printf ("dans FindLengthOB (%04x,%04x)\n",g,n);
558 if (DEBUG) printf("en %d o(%o) x(%x)\n",l,l,l);
562 TotalLength += 4; // We even have to decount the group and element
564 if ( g != 0xfffe && g!=0xb00c ) /*for bogus headerJPR */ {
565 char msg[100]; // for sprintf. Sorry
566 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
567 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
569 if (DEBUG) printf("en %d o(%o) x(%x)\n",l,l,l);
574 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header JPR */
575 FoundSequenceDelimiter = true;
576 else if ( n != 0xe000 ){
577 char msg[100]; // for sprintf. Sorry
578 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
579 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
580 if (DEBUG) printf("wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
584 ItemLength = ReadInt32();
585 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
586 // the ItemLength with ReadInt32
588 if (DEBUG) printf("TotalLength %d\n",TotalLength);
589 SkipBytes(ItemLength);
591 fseek(fp, PositionOnEntry, SEEK_SET);
596 * \ingroup gdcmHeader
601 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
602 guint16 element = ElVal->GetElement();
603 guint16 group = ElVal->GetGroup(); // JPR a virer
604 string vr = ElVal->GetVR();
606 if( (element == 0x0010) && (group == 0x7fe0) ) {// JPR
609 dbg.Verbose(2, "gdcmHeader::FindLength: ", // JPR
610 "on est sur 7fe0 0010");
613 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
614 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
616 // The following reserved two bytes (see PS 3.5-2001, section
617 // 7.1.2 Data element structure with explicit vr p27) must be
618 // skipped before proceeding on reading the length on 4 bytes.
619 fseek(fp, 2L, SEEK_CUR);
621 guint32 length32 = ReadInt32();
622 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
623 ElVal->SetLength(FindLengthOB());
626 FixFoundLength(ElVal, length32);
630 // Length is encoded on 2 bytes.
631 length16 = ReadInt16();
633 // We can tell the current file is encoded in big endian (like
634 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
635 // and it's value is the one of the encoding of a big endian file.
636 // In order to deal with such big endian encoded files, we have
637 // (at least) two strategies:
638 // * when we load the "Transfer Syntax" tag with value of big endian
639 // encoding, we raise the proper flags. Then we wait for the end
640 // of the META group (0x0002) among which is "Transfer Syntax",
641 // before switching the swap code to big endian. We have to postpone
642 // the switching of the swap code since the META group is fully encoded
643 // in little endian, and big endian coding only starts at the next
644 // group. The corresponding code can be hard to analyse and adds
645 // many additional unnecessary tests for regular tags.
646 // * the second strategy consists in waiting for trouble, that shall
647 // appear when we find the first group with big endian encoding. This
648 // is easy to detect since the length of a "Group Length" tag (the
649 // ones with zero as element number) has to be of 4 (0x0004). When we
650 // encouter 1024 (0x0400) chances are the encoding changed and we
651 // found a group with big endian encoding.
652 // We shall use this second strategy. In order to make sure that we
653 // can interpret the presence of an apparently big endian encoded
654 // length of a "Group Length" without committing a big mistake, we
655 // add an additional check: we look in the allready parsed elements
656 // for the presence of a "Transfer Syntax" whose value has to be "big
657 // endian encoding". When this is the case, chances are we have got our
658 // hands on a big endian encoded file: we switch the swap code to
659 // big endian and proceed...
660 if ( (element == 0x0000) && (length16 == 0x0400) ) {
661 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
662 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
667 SwitchSwapToBigEndian();
668 // Restore the unproperly loaded values i.e. the group, the element
669 // and the dictionary entry depending on them.
670 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
671 guint16 CorrectElem = SwapShort(ElVal->GetElement());
672 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
675 // This correct tag is not in the dictionary. Create a new one.
676 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
678 // FIXME this can create a memory leaks on the old entry that be
679 // left unreferenced.
680 ElVal->SetDictEntry(NewTag);
683 // Heuristic: well some files are really ill-formed.
684 if ( length16 == 0xffff) {
686 dbg.Verbose(0, "gdcmHeader::FindLength",
687 "Erroneous element length fixed.");
689 FixFoundLength(ElVal, (guint32)length16);
693 // Either implicit VR or a non DICOM conformal (see not below) explicit
694 // VR that ommited the VR of (at least) this element. Farts happen.
695 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
696 // on Data elements "Implicit and Explicit VR Data Elements shall
697 // not coexist in a Data Set and Data Sets nested within it".]
698 // Length is on 4 bytes.
699 FixFoundLength(ElVal, ReadInt32());
703 * \ingroup gdcmHeader
704 * \brief Swaps back the bytes of 4-byte long integer accordingly to
707 * @return The suggested integer.
709 guint32 gdcmHeader::SwapLong(guint32 a) {
714 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
715 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
719 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
723 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
726 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
733 * \ingroup gdcmHeader
734 * \brief Swaps the bytes so they agree with the processor order
735 * @return The properly swaped 16 bits integer.
737 guint16 gdcmHeader::SwapShort(guint16 a) {
738 if ( (sw==4321) || (sw==2143) )
739 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
744 * \ingroup gdcmHeader
749 void gdcmHeader::SkipBytes(guint32 NBytes) {
750 //FIXME don't dump the returned value
751 (void)fseek(fp, (long)NBytes, SEEK_CUR);
755 * \ingroup gdcmHeader
760 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
761 SkipBytes(ElVal->GetLength());
765 * \ingroup gdcmHeader
770 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
773 if ((guint32)NewSize >= (guint32)0xffffffff) {
774 MaxSizeLoadElementValue = 0xffffffff;
777 MaxSizeLoadElementValue = NewSize;
781 * \ingroup gdcmHeader
782 * \brief Loads the element content if it's length is not bigger
783 * than the value specified with
784 * gdcmHeader::SetMaxSizeLoadElementValue()
786 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
788 guint16 group = ElVal->GetGroup();
789 string vr = ElVal->GetVR();
790 guint32 length = ElVal->GetLength();
791 bool SkipLoad = false;
793 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
795 // FIXME Sequences not treated yet !
797 // Ne faudrait-il pas au contraire trouver immediatement
798 // une maniere 'propre' de traiter les sequences (vr = SQ)
799 // car commencer par les ignorer risque de conduire a qq chose
800 // qui pourrait ne pas etre generalisable
801 // Well, I'm expecting your code !!!
806 // Heuristic : a sequence "contains" a set of tags (called items). It looks
807 // like the last tag of a sequence (the one that terminates the sequence)
808 // has a group of 0xfffe (with a dummy length).
809 if( group == 0xfffe )
814 ElVal->SetValue("gdcm::Skipped");
818 // When the length is zero things are easy:
824 // The elements whose length is bigger than the specified upper bound
825 // are not loaded. Instead we leave a short notice of the offset of
826 // the element content and it's length.
827 if (length > MaxSizeLoadElementValue) {
829 s << "gdcm::NotLoaded.";
830 s << " Address:" << (long)ElVal->GetOffset();
831 s << " Length:" << ElVal->GetLength();
832 ElVal->SetValue(s.str());
836 // When an integer is expected, read and convert the following two or
837 // four bytes properly i.e. as an integer as opposed to a string.
839 // pour les elements de Value Multiplicity > 1
840 // on aura en fait une serie d'entiers
842 // on devrait pouvoir faire + compact (?)
844 if ( IsAnInteger(ElVal) ) {
848 if (vr == "US" || vr == "SS") {
850 NewInt = ReadInt16();
853 for (int i=1; i < nbInt; i++) {
855 NewInt = ReadInt16();
860 } else if (vr == "UL" || vr == "SL") {
862 NewInt = ReadInt32();
865 for (int i=1; i < nbInt; i++) {
867 NewInt = ReadInt32();
872 ElVal->SetValue(s.str());
876 // We need an additional byte for storing \0 that is not on disk
877 char* NewValue = (char*)malloc(length+1);
879 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
884 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
885 if ( item_read != 1 ) {
887 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
888 ElVal->SetValue("gdcm::UnRead");
891 ElVal->SetValue(NewValue);
896 * \ingroup gdcmHeader
897 * \brief Loads the element while preserving the current
898 * underlying file position indicator as opposed to
899 * to LoadElementValue that modifies it.
900 * @param ElVal Element whose value shall be loaded.
903 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
904 long PositionOnEntry = ftell(fp);
905 LoadElementValue(ElVal);
906 fseek(fp, PositionOnEntry, SEEK_SET);
910 * \ingroup gdcmHeader
915 guint16 gdcmHeader::ReadInt16(void) {
918 item_read = fread (&g, (size_t)2,(size_t)1, fp);
919 if ( item_read != 1 ) {
920 dbg.Verbose(1, "gdcmHeader::ReadInt16", " Failed to read :");
922 dbg.Verbose(1, "gdcmHeader::ReadInt16", " End of File encountered");
924 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File Error");
934 * \ingroup gdcmHeader
939 guint32 gdcmHeader::ReadInt32(void) {
942 item_read = fread (&g, (size_t)4,(size_t)1, fp);
943 if ( item_read != 1 ) {
945 dbg.Verbose(1, "gdcmHeader::ReadInt32", " Failed to read :");
947 dbg.Verbose(1, "gdcmHeader::ReadInt32", " End of File encountered");
949 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File Error");
959 * \ingroup gdcmHeader
964 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
966 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
968 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
969 "failed to Locate gdcmElValue");
970 return (gdcmElValue*)0;
976 * \ingroup gdcmHeader
977 * \brief Build a new Element Value from all the low level arguments.
978 * Check for existence of dictionary entry, and build
979 * a default one when absent.
980 * @param Group group of the underlying DictEntry
981 * @param Elem element of the underlying DictEntry
983 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
984 // Find out if the tag we encountered is in the dictionaries:
985 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
987 NewTag = new gdcmDictEntry(Group, Elem);
989 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
991 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
992 "failed to allocate gdcmElValue");
993 return (gdcmElValue*)0;
999 * \ingroup gdcmHeader
1003 int gdcmHeader::ReplaceOrCreateByNumber(string Value, guint16 Group, guint16 Elem ) {
1005 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1006 PubElValSet.Add(nvElValue);
1007 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1012 * \ingroup gdcmHeader
1013 * \brief Build a new Element Value from all the low level arguments.
1014 * Check for existence of dictionary entry, and build
1015 * a default one when absent.
1016 * @param Name Name of the underlying DictEntry
1018 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
1020 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1022 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1024 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1026 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1027 "failed to allocate gdcmElValue");
1028 return (gdcmElValue*)0;
1034 * \ingroup gdcmHeader
1035 * \brief Read the next tag but WITHOUT loading it's value
1036 * @return On succes the newly created ElValue, NULL on failure.
1038 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1041 gdcmElValue * NewElVal;
1046 if ( (g==0x7fe0) && (n==0x0010) )
1048 printf("in gdcmHeader::ReadNextElement try to read 7fe0 0010 \n");
1051 // We reached the EOF (or an error occured) and header parsing
1052 // has to be considered as finished.
1053 return (gdcmElValue *)0;
1055 NewElVal = NewElValueByNumber(g, n);
1057 FindLength(NewElVal);
1060 if (DEBUG) printf("in gdcmHeader::ReadNextElement : g %04x n %04x errno %d\n",g, n, errno);
1061 return (gdcmElValue *)0;
1063 NewElVal->SetOffset(ftell(fp));
1064 if ( (g==0x7fe0) && (n==0x0010) )
1066 printf("sortie de gdcmHeader::ReadNextElement 7fe0 0010 \n");
1071 * \ingroup gdcmHeader
1072 * \brief Apply some heuristics to predict wether the considered
1073 * element value contains/represents an integer or not.
1074 * @param ElVal The element value on which to apply the predicate.
1075 * @return The result of the heuristical predicate.
1077 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1078 guint16 group = ElVal->GetGroup();
1079 guint16 element = ElVal->GetElement();
1080 string vr = ElVal->GetVR();
1081 guint32 length = ElVal->GetLength();
1083 // When we have some semantics on the element we just read, and if we
1084 // a priori know we are dealing with an integer, then we shall be
1085 // able to swap it's element value properly.
1086 if ( element == 0 ) { // This is the group length of the group
1090 if (DEBUG) printf("Erroneous Group Length element length (%04x , %04x) : %d\n",
1091 group, element,length);
1093 dbg.Error("gdcmHeader::IsAnInteger",
1094 "Erroneous Group Length element length.");
1097 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1104 * \ingroup gdcmHeader
1105 * \brief Recover the offset (from the beginning of the file) of the pixels.
1107 size_t gdcmHeader::GetPixelOffset(void) {
1108 // If this file complies with the norm we should encounter the
1109 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1110 // the group that contains the pixel data (hence the "Pixel Data"
1111 // is found by indirection through the "Image Location").
1112 // Inside the group pointed by "Image Location" the searched element
1113 // is conventionally the element 0x0010 (when the norm is respected).
1114 // When the "Image Location" is absent we default to group 0x7fe0.
1117 string ImageLocation = GetPubElValByName("Image Location");
1118 if ( ImageLocation == "gdcm::Unfound" ) {
1121 grPixel = (guint16) atoi( ImageLocation.c_str() );
1123 if (grPixel != 0x7fe0)
1124 // This is a kludge for old dirty Philips imager.
1129 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1132 return PixelElement->GetOffset();
1138 * \ingroup gdcmHeader
1139 * \brief Searches both the public and the shadow dictionary (when they
1140 * exist) for the presence of the DictEntry with given
1141 * group and element. The public dictionary has precedence on the
1143 * @param group group of the searched DictEntry
1144 * @param element element of the searched DictEntry
1145 * @return Corresponding DictEntry when it exists, NULL otherwise.
1147 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1149 gdcmDictEntry * found = (gdcmDictEntry*)0;
1150 if (!RefPubDict && !RefShaDict) {
1151 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1152 "we SHOULD have a default dictionary");
1155 found = RefPubDict->GetTagByNumber(group, element);
1160 found = RefShaDict->GetTagByNumber(group, element);
1168 * \ingroup gdcmHeader
1169 * \brief Searches both the public and the shadow dictionary (when they
1170 * exist) for the presence of the DictEntry with given name.
1171 * The public dictionary has precedence on the shadow one.
1172 * @param Name name of the searched DictEntry
1173 * @return Corresponding DictEntry when it exists, NULL otherwise.
1175 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1176 gdcmDictEntry * found = (gdcmDictEntry*)0;
1177 if (!RefPubDict && !RefShaDict) {
1178 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1179 "we SHOULD have a default dictionary");
1182 found = RefPubDict->GetTagByName(Name);
1187 found = RefShaDict->GetTagByName(Name);
1195 * \ingroup gdcmHeader
1196 * \brief Searches within the public dictionary for element value of
1198 * @param group Group of the researched tag.
1199 * @param element Element of the researched tag.
1200 * @return Corresponding element value when it exists, and the string
1201 * "gdcm::Unfound" otherwise.
1203 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1204 return PubElValSet.GetElValueByNumber(group, element);
1208 * \ingroup gdcmHeader
1209 * \brief Searches within the public dictionary for element value
1210 * representation of a given tag.
1212 * Obtaining the VR (Value Representation) might be needed by caller
1213 * to convert the string typed content to caller's native type
1214 * (think of C++ vs Python). The VR is actually of a higher level
1215 * of semantics than just the native C++ type.
1216 * @param group Group of the researched tag.
1217 * @param element Element of the researched tag.
1218 * @return Corresponding element value representation when it exists,
1219 * and the string "gdcm::Unfound" otherwise.
1221 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1222 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1224 return "gdcm::Unfound";
1225 return elem->GetVR();
1229 * \ingroup gdcmHeader
1230 * \brief Searches within the public dictionary for element value of
1232 * @param TagName name of the researched element.
1233 * @return Corresponding element value when it exists, and the string
1234 * "gdcm::Unfound" otherwise.
1236 string gdcmHeader::GetPubElValByName(string TagName) {
1237 return PubElValSet.GetElValueByName(TagName);
1241 * \ingroup gdcmHeader
1242 * \brief Searches within the elements parsed with the public dictionary for
1243 * the element value representation of a given tag.
1245 * Obtaining the VR (Value Representation) might be needed by caller
1246 * to convert the string typed content to caller's native type
1247 * (think of C++ vs Python). The VR is actually of a higher level
1248 * of semantics than just the native C++ type.
1249 * @param TagName name of the researched element.
1250 * @return Corresponding element value representation when it exists,
1251 * and the string "gdcm::Unfound" otherwise.
1253 string gdcmHeader::GetPubElValRepByName(string TagName) {
1254 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1256 return "gdcm::Unfound";
1257 return elem->GetVR();
1261 * \ingroup gdcmHeader
1262 * \brief Searches within elements parsed with the SHADOW dictionary
1263 * for the element value of a given tag.
1264 * @param group Group of the researched tag.
1265 * @param element Element of the researched tag.
1266 * @return Corresponding element value representation when it exists,
1267 * and the string "gdcm::Unfound" otherwise.
1269 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1270 return ShaElValSet.GetElValueByNumber(group, element);
1274 * \ingroup gdcmHeader
1275 * \brief Searches within the elements parsed with the SHADOW dictionary
1276 * for the element value representation of a given tag.
1278 * Obtaining the VR (Value Representation) might be needed by caller
1279 * to convert the string typed content to caller's native type
1280 * (think of C++ vs Python). The VR is actually of a higher level
1281 * of semantics than just the native C++ type.
1282 * @param group Group of the researched tag.
1283 * @param element Element of the researched tag.
1284 * @return Corresponding element value representation when it exists,
1285 * and the string "gdcm::Unfound" otherwise.
1287 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1288 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1290 return "gdcm::Unfound";
1291 return elem->GetVR();
1295 * \ingroup gdcmHeader
1296 * \brief Searches within the elements parsed with the shadow dictionary
1297 * for an element value of given tag.
1298 * @param TagName name of the researched element.
1299 * @return Corresponding element value when it exists, and the string
1300 * "gdcm::Unfound" otherwise.
1302 string gdcmHeader::GetShaElValByName(string TagName) {
1303 return ShaElValSet.GetElValueByName(TagName);
1307 * \ingroup gdcmHeader
1308 * \brief Searches within the elements parsed with the shadow dictionary for
1309 * the element value representation of a given tag.
1311 * Obtaining the VR (Value Representation) might be needed by caller
1312 * to convert the string typed content to caller's native type
1313 * (think of C++ vs Python). The VR is actually of a higher level
1314 * of semantics than just the native C++ type.
1315 * @param TagName name of the researched element.
1316 * @return Corresponding element value representation when it exists,
1317 * and the string "gdcm::Unfound" otherwise.
1319 string gdcmHeader::GetShaElValRepByName(string TagName) {
1320 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1322 return "gdcm::Unfound";
1323 return elem->GetVR();
1327 * \ingroup gdcmHeader
1328 * \brief Searches within elements parsed with the public dictionary
1329 * and then within the elements parsed with the shadow dictionary
1330 * for the element value of a given tag.
1331 * @param group Group of the researched tag.
1332 * @param element Element of the researched tag.
1333 * @return Corresponding element value representation when it exists,
1334 * and the string "gdcm::Unfound" otherwise.
1336 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1337 string pub = GetPubElValByNumber(group, element);
1340 return GetShaElValByNumber(group, element);
1344 * \ingroup gdcmHeader
1345 * \brief Searches within elements parsed with the public dictionary
1346 * and then within the elements parsed with the shadow dictionary
1347 * for the element value representation of a given tag.
1349 * Obtaining the VR (Value Representation) might be needed by caller
1350 * to convert the string typed content to caller's native type
1351 * (think of C++ vs Python). The VR is actually of a higher level
1352 * of semantics than just the native C++ type.
1353 * @param group Group of the researched tag.
1354 * @param element Element of the researched tag.
1355 * @return Corresponding element value representation when it exists,
1356 * and the string "gdcm::Unfound" otherwise.
1358 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1359 string pub = GetPubElValRepByNumber(group, element);
1362 return GetShaElValRepByNumber(group, element);
1366 * \ingroup gdcmHeader
1367 * \brief Searches within elements parsed with the public dictionary
1368 * and then within the elements parsed with the shadow dictionary
1369 * for the element value of a given tag.
1370 * @param TagName name of the researched element.
1371 * @return Corresponding element value when it exists,
1372 * and the string "gdcm::Unfound" otherwise.
1374 string gdcmHeader::GetElValByName(string TagName) {
1375 string pub = GetPubElValByName(TagName);
1378 return GetShaElValByName(TagName);
1382 * \ingroup gdcmHeader
1383 * \brief Searches within elements parsed with the public dictionary
1384 * and then within the elements parsed with the shadow dictionary
1385 * for the element value representation of a given tag.
1387 * Obtaining the VR (Value Representation) might be needed by caller
1388 * to convert the string typed content to caller's native type
1389 * (think of C++ vs Python). The VR is actually of a higher level
1390 * of semantics than just the native C++ type.
1391 * @param TagName name of the researched element.
1392 * @return Corresponding element value representation when it exists,
1393 * and the string "gdcm::Unfound" otherwise.
1395 string gdcmHeader::GetElValRepByName(string TagName) {
1396 string pub = GetPubElValRepByName(TagName);
1399 return GetShaElValRepByName(TagName);
1403 * \ingroup gdcmHeader
1404 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1405 * through it's (group, element) and modifies it's content with
1407 * @param content new value to substitute with
1408 * @param group group of the ElVal to modify
1409 * @param element element of the ElVal to modify
1411 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1414 //TODO : homogeneiser les noms : SetPubElValByNumber qui appelle PubElValSet.SetElValueByNumber
1415 // pourquoi pas SetPubElValueByNumber ??
1418 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1422 * \ingroup gdcmHeader
1423 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1424 * through tag name and modifies it's content with the given value.
1425 * @param content new value to substitute with
1426 * @param TagName name of the tag to be modified
1428 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1429 return ( PubElValSet.SetElValueByName (content, TagName) );
1433 * \ingroup gdcmHeader
1434 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1435 * through it's (group, element) and modifies it's length with
1437 * \warning Use with extreme caution.
1438 * @param length new length to substitute with
1439 * @param group group of the ElVal to modify
1440 * @param element element of the ElVal to modify
1441 * @return 1 on success, 0 otherwise.
1444 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1446 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1450 * \ingroup gdcmHeader
1451 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1452 * through it's (group, element) and modifies it's content with
1454 * @param content new value to substitute with
1455 * @param group group of the ElVal to modify
1456 * @param element element of the ElVal to modify
1457 * @return 1 on success, 0 otherwise.
1459 int gdcmHeader::SetShaElValByNumber(string content,
1460 guint16 group, guint16 element) {
1461 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1465 * \ingroup gdcmHeader
1466 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1467 * through tag name and modifies it's content with the given value.
1468 * @param content new value to substitute with
1469 * @param TagName name of the tag to be modified
1471 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1472 return ( ShaElValSet.SetElValueByName (content, TagName) );
1476 * \ingroup gdcmHeader
1477 * \brief Parses the header of the file but WITHOUT loading element values.
1479 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1480 gdcmElValue * newElValue = (gdcmElValue *)0;
1484 while ( (newElValue = ReadNextElement()) ) {
1485 SkipElementValue(newElValue);
1486 PubElValSet.Add(newElValue);
1493 // des que les element values sont chargees, stocker,
1494 // en une seule fois, dans des entiers
1495 // NX, NY, NZ, Bits allocated, Bits Stored, High Bit, Samples Per Pixel
1496 // (TODO : preciser les autres)
1497 // et refaire ceux des accesseurs qui renvoient les entiers correspondants
1499 // --> peut etre dangereux ?
1500 // si l'utilisateur modifie 'manuellement' l'un des paramètres
1501 // l'entier de sera pas modifié ...
1502 // (pb de la mise à jour en cas de redondance :-(
1505 * \ingroup gdcmHeader
1506 * \brief Retrieve the number of columns of image.
1507 * @return The encountered size when found, 0 by default.
1509 int gdcmHeader::GetXSize(void) {
1510 // We cannot check for "Columns" because the "Columns" tag is present
1511 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1512 string StrSize = GetPubElValByNumber(0x0028,0x0011);
1513 if (StrSize == "gdcm::Unfound")
1515 return atoi(StrSize.c_str());
1519 * \ingroup gdcmHeader
1520 * \brief Retrieve the number of lines of image.
1521 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1522 * @return The encountered size when found, 1 by default.
1524 int gdcmHeader::GetYSize(void) {
1525 // We cannot check for "Rows" because the "Rows" tag is present
1526 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1527 string StrSize = GetPubElValByNumber(0x0028,0x0010);
1528 if (StrSize != "gdcm::Unfound")
1529 return atoi(StrSize.c_str());
1533 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1534 // hence be a signal (1d image). So we default to 1:
1539 * \ingroup gdcmHeader
1540 * \brief Retrieve the number of planes of volume or the number
1541 * of frames of a multiframe.
1542 * \warning When present we consider the "Number of Frames" as the third
1543 * dimension. When absent we consider the third dimension as
1544 * being the "Planes" tag content.
1545 * @return The encountered size when found, 1 by default.
1547 int gdcmHeader::GetZSize(void) {
1548 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1549 // as the third dimension.
1550 string StrSize = GetPubElValByNumber(0x0028,0x0008);
1551 if (StrSize != "gdcm::Unfound")
1552 return atoi(StrSize.c_str());
1554 // We then consider the "Planes" entry as the third dimension [we
1555 // cannot retrieve by name since "Planes tag is present both in
1556 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1557 StrSize = GetPubElValByNumber(0x0028,0x0012);
1558 if (StrSize != "gdcm::Unfound")
1559 return atoi(StrSize.c_str());
1565 * \ingroup gdcmHeader
1566 * \brief Retrieve the number of Bits Stored
1567 * (as opposite to number of Bits Allocated)
1569 * @return The encountered number of Bits Stored, 0 by default.
1571 int gdcmHeader::GetBitsStored(void) {
1572 string StrSize = GetPubElValByNumber(0x0028,0x0101);
1573 if (StrSize == "gdcm::Unfound")
1575 return atoi(StrSize.c_str());
1580 * \ingroup gdcmHeader
1581 * \brief Retrieve the number of Samples Per Pixel
1582 * (1 : gray level, 3 : RGB)
1584 * @return The encountered number of Samples Per Pixel, 1 by default.
1586 int gdcmHeader::GetSamplesPerPixel(void) {
1587 string StrSize = GetPubElValByNumber(0x0028,0x0002);
1588 if (StrSize == "gdcm::Unfound")
1589 return 1; // Well, it's supposed to be mandatory ...
1590 return atoi(StrSize.c_str());
1593 * \ingroup gdcmHeader
1594 * \brief Return the size (in bytes) of a single pixel of data.
1595 * @return The size in bytes of a single pixel of data.
1598 int gdcmHeader::GetPixelSize(void) {
1599 string PixelType = GetPixelType();
1600 if (PixelType == "8U" || PixelType == "8S")
1602 if (PixelType == "16U" || PixelType == "16S")
1604 if (PixelType == "32U" || PixelType == "32S")
1606 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1611 * \ingroup gdcmHeader
1612 * \brief Build the Pixel Type of the image.
1613 * Possible values are:
1614 * - 8U unsigned 8 bit,
1615 * - 8S signed 8 bit,
1616 * - 16U unsigned 16 bit,
1617 * - 16S signed 16 bit,
1618 * - 32U unsigned 32 bit,
1619 * - 32S signed 32 bit,
1620 * \warning 12 bit images appear as 16 bit.
1623 string gdcmHeader::GetPixelType(void) {
1625 BitsAlloc = GetElValByName("Bits Allocated");
1626 if (BitsAlloc == "gdcm::Unfound") {
1627 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1628 BitsAlloc = string("16");
1630 if (BitsAlloc == "12")
1631 BitsAlloc = string("16");
1634 Signed = GetElValByName("Pixel Representation");
1635 if (Signed == "gdcm::Unfound") {
1636 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1637 BitsAlloc = string("0");
1640 Signed = string("U");
1642 Signed = string("S");
1644 return( BitsAlloc + Signed);
1649 * \ingroup gdcmHeader
1650 * \brief This predicate, based on hopefully reasonnable heuristics,
1651 * decides whether or not the current gdcmHeader was properly parsed
1652 * and contains the mandatory information for being considered as
1653 * a well formed and usable image.
1654 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1657 bool gdcmHeader::IsReadable(void) {
1658 if ( GetElValByName("Image Dimensions") != "gdcm::Unfound"
1659 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1662 if ( GetElValByName("Bits Allocated") == "gdcm::Unfound" )
1664 if ( GetElValByName("Bits Stored") == "gdcm::Unfound" )
1666 if ( GetElValByName("High Bit") == "gdcm::Unfound" )
1668 if ( GetElValByName("Pixel Representation") == "gdcm::Unfound" )
1674 * \ingroup gdcmHeader
1675 * \brief Small utility function that creates a new manually crafted
1676 * (as opposed as read from the file) gdcmElValue with user
1677 * specified name and adds it to the public tag hash table.
1678 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1679 * @param NewTagName The name to be given to this new tag.
1680 * @param VR The Value Representation to be given to this new tag.
1681 * @ return The newly hand crafted Element Value.
1683 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1684 gdcmElValue* NewElVal = (gdcmElValue*)0;
1685 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1686 guint32 FreeElem = 0;
1687 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1689 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1690 if (FreeElem == UINT32_MAX) {
1691 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1692 "Group 0xffff in Public Dict is full");
1693 return (gdcmElValue*)0;
1695 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1696 VR, "GDCM", NewTagName);
1697 NewElVal = new gdcmElValue(NewEntry);
1698 PubElValSet.Add(NewElVal);
1703 * \ingroup gdcmHeader
1704 * \brief Loads the element values of all the elements present in the
1705 * public tag based hash table.
1707 void gdcmHeader::LoadElements(void) {
1709 TagElValueHT ht = PubElValSet.GetTagHt();
1710 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1711 LoadElementValue(tag->second);
1716 * \ingroup gdcmHeader
1720 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1721 PubElValSet.Print(os);
1725 * \ingroup gdcmHeader
1729 void gdcmHeader::PrintPubDict(std::ostream & os) {
1730 RefPubDict->Print(os);
1734 * \ingroup gdcmHeader
1739 int gdcmHeader::Write(FILE * fp, FileType type) {
1740 return PubElValSet.Write(fp, type);
1744 * \ingroup gdcmHeader
1748 float gdcmHeader::GetXSpacing(void) {
1749 float xspacing, yspacing;
1750 string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1752 if (StrSpacing == "gdcm::Unfound") {
1753 dbg.Verbose(0, "gdcmHeader::GetXSpacing: unfound Pixel Spacing");
1756 if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1763 * \ingroup gdcmHeader
1767 float gdcmHeader::GetYSpacing(void) {
1768 float xspacing, yspacing;
1769 string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1771 if (StrSpacing == "gdcm::Unfound") {
1772 dbg.Verbose(0, "gdcmHeader::GetYSpacing: unfound Pixel Spacing");
1776 if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1781 dbg.Verbose(0, "gdcmHeader::GetYSpacing: gdcmData/CT-MONO2-8-abdo.dcm problem");
1782 // seems to be a bug in the header ...
1783 sscanf( StrSpacing.c_str(), "%f\\0\\%f", &xspacing, &yspacing);
1790 * \ingroup gdcmHeader
1794 float gdcmHeader::GetZSpacing(void) {
1795 // TODO : translate into English
1796 // Spacing Between Slices : distance entre le milieu de chaque coupe
1797 // Les coupes peuvent etre :
1798 // jointives (Spacing between Slices = Slice Thickness)
1799 // chevauchantes (Spacing between Slices < Slice Thickness)
1800 // disjointes (Spacing between Slices > Slice Thickness)
1801 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
1802 // ca interesse le physicien de l'IRM, pas le visualisateur de volumes ...
1803 // Si le Spacing Between Slices est absent,
1804 // on suppose que les coupes sont jointives
1806 string StrSpacingBSlices = GetPubElValByNumber(0x0018,0x0088);
1808 if (StrSpacingBSlices == "gdcm::Unfound") {
1809 dbg.Verbose(0, "gdcmHeader::GetZSpacing: unfound StrSpacingBSlices");
1810 string StrSliceThickness = GetPubElValByNumber(0x0018,0x0050);
1811 if (StrSliceThickness == "gdcm::Unfound")
1814 return atof(StrSliceThickness.c_str());
1816 return atof(StrSpacingBSlices.c_str());
1821 // Image Position Patient :
1822 // If not found (AVR-NEMA), we consider Slice Location (20,1041)
1823 // or Location (20,50) as the Z coordinate,
1824 // 0. for all the coordinates if Slice Location not found
1825 // TODO : find a way to inform the caller nothing was found
1826 // TODO : How to tell the caller a wrong number of values was found?
1828 * \ingroup gdcmHeader
1832 float gdcmHeader::GetXImagePosition(void) {
1833 float xImPos, yImPos, zImPos;
1834 // 0020,0032 : Image Position Patient
1835 // 0020,1041 : Slice Location
1836 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1838 if (StrImPos == "gdcm::Unfound") {
1839 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Image Position Patient");
1840 string StrSliceLoc = GetPubElValByNumber(0x0020,0x1041);
1841 if (StrSliceLoc == "gdcm::Unfound") {
1842 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Slice Location");
1843 // How to tell the caller nothing was found?
1847 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1848 // How to tell the caller a wrong number of values was found?
1855 * \ingroup gdcmHeader
1859 float gdcmHeader::GetYImagePosition(void) {
1860 float xImPos, yImPos, zImPos;
1861 // 0020,0032 : Image Position Patient
1862 // 0020,1041 : Slice Location
1863 // 0020,0050 : Location
1864 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1866 if (StrImPos == "gdcm::Unfound") {
1867 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position Patient");
1868 string StrSliceLoc = GetPubElValByNumber(0x0020,0x1041);
1869 if (StrSliceLoc == "gdcm::Unfound") {
1870 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
1871 // How to tell the caller nothing was found?
1872 string StrLocation = GetPubElValByNumber(0x0020,0x0050);
1873 if (StrSliceLoc == "gdcm::Unfound") {
1874 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
1879 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1880 // How to tell the caller a wrong number of values was found?
1887 * \ingroup gdcmHeader
1891 float gdcmHeader::GetZImagePosition(void) {
1892 float xImPos, yImPos, zImPos;
1893 // 0020,0032 : Image Position Patient
1894 // 0020,1041 : Slice Location
1895 // 0020,0050 : Location
1897 // TODO : How to tell the caller nothing was found?
1898 // TODO : How to tell the caller a wrong number of values was found?
1900 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1901 if (StrImPos != "gdcm::Unfound") {
1902 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3) {
1903 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Image Position Patient");
1904 return 0.; // bug in the element 0x0020,0x0032
1909 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position Patient");
1911 string StrSliceLocation = GetPubElValByNumber(0x0020,0x1041);
1912 if (StrSliceLocation != "gdcm::Unfound") {
1913 if( sscanf( StrSliceLocation.c_str(), "%f", &zImPos) !=1) {
1914 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Slice Location");
1915 return 0.; // bug in the element 0x0020,0x1041
1920 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
1922 string StrLocation = GetPubElValByNumber(0x0020,0x0050);
1923 if (StrLocation != "gdcm::Unfound") {
1924 if( sscanf( StrLocation.c_str(), "%f", &zImPos) !=1) {
1925 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Location");
1926 return 0.; // bug in the element 0x0020,0x0050
1931 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
1933 return 0.; // Hopeless