2 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.74 2003/07/01 15:48:27 jpr Exp $
10 #include <netinet/in.h>
12 #include <cctype> // for isalpha
15 #include "gdcmHeader.h"
19 // TODO : remove DEBUG
22 // Refer to gdcmHeader::CheckSwap()
23 #define HEADER_LENGTH_TO_READ 256
24 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
25 #define _MaxSizeLoadElementValue_ 1024
31 void gdcmHeader::Initialise(void) {
32 dicom_vr = gdcmGlobal::GetVR();
33 dicom_ts = gdcmGlobal::GetTS();
34 Dicts = gdcmGlobal::GetDicts();
35 RefPubDict = Dicts->GetDefaultPubDict();
36 RefShaDict = (gdcmDict*)0;
43 * @param exception_on_error
45 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) {
46 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
47 filename = InFilename;
49 if ( !OpenFile(exception_on_error))
59 * @param exception_on_error
61 gdcmHeader::gdcmHeader(bool exception_on_error) {
62 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
69 * @param exception_on_error
72 bool gdcmHeader::OpenFile(bool exception_on_error)
73 throw(gdcmFileError) {
74 fp=fopen(filename.c_str(),"rb");
75 if(exception_on_error) {
77 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
81 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
90 bool gdcmHeader::CloseFile(void) {
91 int closed = fclose(fp);
100 * \brief Canonical destructor.
102 gdcmHeader::~gdcmHeader (void) {
103 dicom_vr = (gdcmVR*)0;
104 Dicts = (gdcmDictSet*)0;
105 RefPubDict = (gdcmDict*)0;
106 RefShaDict = (gdcmDict*)0;
112 // META Meta Information
124 // NMI Nuclear Medicine
126 // BFS Basic Film Session
127 // BFB Basic Film Box
128 // BIB Basic Image Box
143 * \ingroup gdcmHeader
144 * \brief Discover what the swap code is (among little endian, big endian,
145 * bad little endian, bad big endian).
148 void gdcmHeader::CheckSwap()
150 // The only guaranted way of finding the swap code is to find a
151 // group tag since we know it's length has to be of four bytes i.e.
152 // 0x00000004. Finding the swap code in then straigthforward. Trouble
153 // occurs when we can't find such group...
155 guint32 x=4; // x : pour ntohs
156 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
160 char deb[HEADER_LENGTH_TO_READ];
162 // First, compare HostByteOrder and NetworkByteOrder in order to
163 // determine if we shall need to swap bytes (i.e. the Endian type).
169 // The easiest case is the one of a DICOM header, since it possesses a
170 // file preamble where it suffice to look for the string "DICM".
171 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
174 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
175 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
176 // Next, determine the value representation (VR). Let's skip to the
177 // first element (0002, 0000) and check there if we find "UL"
178 // - or "OB" if the 1st one is (0002,0001) -,
179 // in which case we (almost) know it is explicit VR.
180 // WARNING: if it happens to be implicit VR then what we will read
181 // is the length of the group. If this ascii representation of this
182 // length happens to be "UL" then we shall believe it is explicit VR.
183 // FIXME: in order to fix the above warning, we could read the next
184 // element value (or a couple of elements values) in order to make
185 // sure we are not commiting a big mistake.
187 // * the 128 bytes of File Preamble (often padded with zeroes),
188 // * the 4 bytes of "DICM" string,
189 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
190 // i.e. a total of 136 bytes.
193 // Use gdcmHeader::dicom_vr to test all the possibilities
194 // instead of just checking for UL, OB and UI !?
195 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
196 (memcmp(entCur, "OB", (size_t)2) == 0) ||
197 (memcmp(entCur, "UI", (size_t)2) == 0) )
199 filetype = ExplicitVR;
200 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
201 "explicit Value Representation");
203 filetype = ImplicitVR;
204 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
205 "not an explicit Value Representation");
210 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
211 "HostByteOrder != NetworkByteOrder");
214 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
215 "HostByteOrder = NetworkByteOrder");
218 // Position the file position indicator at first tag (i.e.
219 // after the file preamble and the "DICM" string).
221 fseek (fp, 132L, SEEK_SET);
225 // Alas, this is not a DicomV3 file and whatever happens there is no file
226 // preamble. We can reset the file position indicator to where the data
227 // is (i.e. the beginning of the file).
228 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
231 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
232 // By clean we mean that the length of the first tag is written down.
233 // If this is the case and since the length of the first group HAS to be
234 // four (bytes), then determining the proper swap code is straightforward.
237 // We assume the array of char we are considering contains the binary
238 // representation of a 32 bits integer. Hence the following dirty
240 s = *((guint32 *)(entCur));
260 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
261 "ACR/NEMA unfound swap info (time to raise bets)");
264 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
265 // It is time for despaired wild guesses. So, let's assume this file
266 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
267 // not present. Then the only info we have is the net2host one.
277 * \ingroup gdcmHeader
280 void gdcmHeader::SwitchSwapToBigEndian(void) {
281 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
282 "Switching to BigEndian mode.");
300 * \ingroup gdcmHeader
301 * \brief Find the value representation of the current tag.
303 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
304 if (filetype != ExplicitVR)
310 char msg[100]; // for sprintf. Sorry
312 long PositionOnEntry = ftell(fp);
313 // Warning: we believe this is explicit VR (Value Representation) because
314 // we used a heuristic that found "UL" in the first tag. Alas this
315 // doesn't guarantee that all the tags will be in explicit VR. In some
316 // cases (see e-film filtered files) one finds implicit VR tags mixed
317 // within an explicit VR file. Hence we make sure the present tag
318 // is in explicit VR and try to fix things if it happens not to be
320 bool RealExplicit = true;
322 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
326 // Assume we are reading a falsely explicit VR file i.e. we reached
327 // a tag where we expect reading a VR but are in fact we read the
328 // first to bytes of the length. Then we will interogate (through find)
329 // the dicom_vr dictionary with oddities like "\004\0" which crashes
330 // both GCC and VC++ implementations of the STL map. Hence when the
331 // expected VR read happens to be non-ascii characters we consider
332 // we hit falsely explicit VR tag.
334 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
335 RealExplicit = false;
337 // CLEANME searching the dicom_vr at each occurence is expensive.
338 // PostPone this test in an optional integrity check at the end
339 // of parsing or only in debug mode.
340 if ( RealExplicit && !dicom_vr->Count(vr) )
343 if ( RealExplicit ) {
344 if ( ElVal->IsVrUnknown() ) {
345 // When not a dictionary entry, we can safely overwrite the vr.
349 if ( ElVal->GetVR() == vr ) {
350 // The vr we just read and the dictionary agree. Nothing to do.
353 // The vr present in the file and the dictionary disagree. We assume
354 // the file writer knew best and use the vr of the file. Since it would
355 // be unwise to overwrite the vr of a dictionary (since it would
356 // compromise it's next user), we need to clone the actual DictEntry
357 // and change the vr for the read one.
358 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
363 ElVal->SetDictEntry(NewTag);
367 // We thought this was explicit VR, but we end up with an
368 // implicit VR tag. Let's backtrack.
370 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", ElVal->GetGroup(),ElVal->GetElement());
371 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
373 fseek(fp, PositionOnEntry, SEEK_SET);
374 // When this element is known in the dictionary we shall use, e.g. for
375 // the semantics (see the usage of IsAnInteger), the vr proposed by the
376 // dictionary entry. Still we have to flag the element as implicit since
377 // we know now our assumption on expliciteness is not furfilled.
379 if ( ElVal->IsVrUnknown() )
380 ElVal->SetVR("Implicit");
381 ElVal->SetImplicitVr();
385 * \ingroup gdcmHeader
386 * \brief Determines if the Transfer Syntax was allready encountered
387 * and if it corresponds to a ImplicitVRLittleEndian one.
389 * @return True when ImplicitVRLittleEndian found. False in all other cases.
391 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
392 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
395 LoadElementValueSafe(Element);
396 string Transfer = Element->GetValue();
397 if ( Transfer == "1.2.840.10008.1.2" )
403 * \ingroup gdcmHeader
404 * \brief Determines if the Transfer Syntax was allready encountered
405 * and if it corresponds to a ExplicitVRLittleEndian one.
407 * @return True when ExplicitVRLittleEndian found. False in all other cases.
409 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
410 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
413 LoadElementValueSafe(Element);
414 string Transfer = Element->GetValue();
415 if ( Transfer == "1.2.840.10008.1.2.1" )
421 * \ingroup gdcmHeader
422 * \brief Determines if the Transfer Syntax was allready encountered
423 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
425 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
427 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
428 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
431 LoadElementValueSafe(Element);
432 string Transfer = Element->GetValue();
433 if ( Transfer == "1.2.840.10008.1.2.1.99" )
439 * \ingroup gdcmHeader
440 * \brief Determines if the Transfer Syntax was allready encountered
441 * and if it corresponds to a Explicit VR Big Endian one.
443 * @return True when big endian found. False in all other cases.
445 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
446 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
449 LoadElementValueSafe(Element);
450 string Transfer = Element->GetValue();
451 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
457 * \ingroup gdcmHeader
458 * \brief Determines if the Transfer Syntax was allready encountered
459 * and if it corresponds to a JPEGBaseLineProcess1 one.
461 * @return True when JPEGBaseLineProcess1found. False in all other cases.
463 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
464 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
467 LoadElementValueSafe(Element);
468 string Transfer = Element->GetValue();
469 if ( Transfer == "1.2.840.10008.1.2.4.50" )
475 * \ingroup gdcmHeader
480 bool gdcmHeader::IsJPEGLossless(void) {
481 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
482 // faire qq chose d'intelligent a la place de ça
485 LoadElementValueSafe(Element);
486 const char * Transfert = Element->GetValue().c_str();
487 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
488 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
494 * \ingroup gdcmHeader
495 * \brief Determines if the Transfer Syntax was allready encountered
496 * and if it corresponds to a JPEGExtendedProcess2-4 one.
498 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
500 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
501 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
504 LoadElementValueSafe(Element);
505 string Transfer = Element->GetValue();
506 if ( Transfer == "1.2.840.10008.1.2.4.51" )
512 * \ingroup gdcmHeader
513 * \brief Determines if the Transfer Syntax was allready encountered
514 * and if it corresponds to a JPEGExtendeProcess3-5 one.
516 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
518 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
519 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
522 LoadElementValueSafe(Element);
523 string Transfer = Element->GetValue();
524 if ( Transfer == "1.2.840.10008.1.2.4.52" )
530 * \ingroup gdcmHeader
531 * \brief Determines if the Transfer Syntax was allready encountered
532 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
534 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
537 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
538 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
541 LoadElementValueSafe(Element);
542 string Transfer = Element->GetValue();
543 if ( Transfer == "1.2.840.10008.1.2.4.53" )
549 * \ingroup gdcmHeader
550 * \brief Predicate for dicom version 3 file.
551 * @return True when the file is a dicom version 3.
553 bool gdcmHeader::IsDicomV3(void) {
554 if ( (filetype == ExplicitVR)
555 || (filetype == ImplicitVR) )
561 * \ingroup gdcmHeader
562 * \brief When the length of an element value is obviously wrong (because
563 * the parser went Jabberwocky) one can hope improving things by
564 * applying this heuristic.
566 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
567 if ( FoundLength == 0xffffffff)
569 ElVal->SetLength(FoundLength);
573 * \ingroup gdcmHeader
578 guint32 gdcmHeader::FindLengthOB(void) {
579 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
582 long PositionOnEntry = ftell(fp);
583 bool FoundSequenceDelimiter = false;
584 guint32 TotalLength = 0;
587 while ( ! FoundSequenceDelimiter) {
591 if (DEBUG) printf ("dans FindLengthOB (%04x,%04x)\n",g,n);
593 if (DEBUG) printf("en %d o(%o) x(%x)\n",l,l,l);
597 TotalLength += 4; // We even have to decount the group and element
599 if ( g != 0xfffe && g!=0xb00c ) /*for bogus headerJPR */ {
600 char msg[100]; // for sprintf. Sorry
601 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
602 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
604 if (DEBUG) printf("en %d o(%o) x(%x)\n",l,l,l);
609 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header JPR */
610 FoundSequenceDelimiter = true;
611 else if ( n != 0xe000 ){
612 char msg[100]; // for sprintf. Sorry
613 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
614 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
615 if (DEBUG) printf("wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
619 ItemLength = ReadInt32();
620 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
621 // the ItemLength with ReadInt32
623 if (DEBUG) printf("TotalLength %d\n",TotalLength);
624 SkipBytes(ItemLength);
626 fseek(fp, PositionOnEntry, SEEK_SET);
631 * \ingroup gdcmHeader
636 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
637 guint16 element = ElVal->GetElement();
638 guint16 group = ElVal->GetGroup(); // JPR a virer
639 string vr = ElVal->GetVR();
641 if( (element == 0x0010) && (group == 0x7fe0) ) {// JPR
644 dbg.Verbose(2, "gdcmHeader::FindLength: ", // JPR
645 "on est sur 7fe0 0010");
648 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
649 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
651 // The following reserved two bytes (see PS 3.5-2001, section
652 // 7.1.2 Data element structure with explicit vr p27) must be
653 // skipped before proceeding on reading the length on 4 bytes.
654 fseek(fp, 2L, SEEK_CUR);
656 guint32 length32 = ReadInt32();
657 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
658 ElVal->SetLength(FindLengthOB());
661 FixFoundLength(ElVal, length32);
665 // Length is encoded on 2 bytes.
666 length16 = ReadInt16();
668 // We can tell the current file is encoded in big endian (like
669 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
670 // and it's value is the one of the encoding of a big endian file.
671 // In order to deal with such big endian encoded files, we have
672 // (at least) two strategies:
673 // * when we load the "Transfer Syntax" tag with value of big endian
674 // encoding, we raise the proper flags. Then we wait for the end
675 // of the META group (0x0002) among which is "Transfer Syntax",
676 // before switching the swap code to big endian. We have to postpone
677 // the switching of the swap code since the META group is fully encoded
678 // in little endian, and big endian coding only starts at the next
679 // group. The corresponding code can be hard to analyse and adds
680 // many additional unnecessary tests for regular tags.
681 // * the second strategy consists in waiting for trouble, that shall
682 // appear when we find the first group with big endian encoding. This
683 // is easy to detect since the length of a "Group Length" tag (the
684 // ones with zero as element number) has to be of 4 (0x0004). When we
685 // encouter 1024 (0x0400) chances are the encoding changed and we
686 // found a group with big endian encoding.
687 // We shall use this second strategy. In order to make sure that we
688 // can interpret the presence of an apparently big endian encoded
689 // length of a "Group Length" without committing a big mistake, we
690 // add an additional check: we look in the allready parsed elements
691 // for the presence of a "Transfer Syntax" whose value has to be "big
692 // endian encoding". When this is the case, chances are we have got our
693 // hands on a big endian encoded file: we switch the swap code to
694 // big endian and proceed...
695 if ( (element == 0x0000) && (length16 == 0x0400) ) {
696 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
697 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
702 SwitchSwapToBigEndian();
703 // Restore the unproperly loaded values i.e. the group, the element
704 // and the dictionary entry depending on them.
705 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
706 guint16 CorrectElem = SwapShort(ElVal->GetElement());
707 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
710 // This correct tag is not in the dictionary. Create a new one.
711 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
713 // FIXME this can create a memory leaks on the old entry that be
714 // left unreferenced.
715 ElVal->SetDictEntry(NewTag);
718 // Heuristic: well some files are really ill-formed.
719 if ( length16 == 0xffff) {
721 dbg.Verbose(0, "gdcmHeader::FindLength",
722 "Erroneous element length fixed.");
724 FixFoundLength(ElVal, (guint32)length16);
728 // Either implicit VR or a non DICOM conformal (see not below) explicit
729 // VR that ommited the VR of (at least) this element. Farts happen.
730 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
731 // on Data elements "Implicit and Explicit VR Data Elements shall
732 // not coexist in a Data Set and Data Sets nested within it".]
733 // Length is on 4 bytes.
734 FixFoundLength(ElVal, ReadInt32());
738 * \ingroup gdcmHeader
739 * \brief Swaps back the bytes of 4-byte long integer accordingly to
742 * @return The suggested integer.
744 guint32 gdcmHeader::SwapLong(guint32 a) {
749 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
750 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
754 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
758 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
761 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
768 * \ingroup gdcmHeader
769 * \brief Swaps the bytes so they agree with the processor order
770 * @return The properly swaped 16 bits integer.
772 guint16 gdcmHeader::SwapShort(guint16 a) {
773 if ( (sw==4321) || (sw==2143) )
774 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
779 * \ingroup gdcmHeader
784 void gdcmHeader::SkipBytes(guint32 NBytes) {
785 //FIXME don't dump the returned value
786 (void)fseek(fp, (long)NBytes, SEEK_CUR);
790 * \ingroup gdcmHeader
795 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
796 SkipBytes(ElVal->GetLength());
800 * \ingroup gdcmHeader
805 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
808 if ((guint32)NewSize >= (guint32)0xffffffff) {
809 MaxSizeLoadElementValue = 0xffffffff;
812 MaxSizeLoadElementValue = NewSize;
816 * \ingroup gdcmHeader
817 * \brief Loads the element content if it's length is not bigger
818 * than the value specified with
819 * gdcmHeader::SetMaxSizeLoadElementValue()
821 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
823 guint16 group = ElVal->GetGroup();
824 string vr = ElVal->GetVR();
825 guint32 length = ElVal->GetLength();
826 bool SkipLoad = false;
828 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
830 // FIXME Sequences not treated yet !
832 // Ne faudrait-il pas au contraire trouver immediatement
833 // une maniere 'propre' de traiter les sequences (vr = SQ)
834 // car commencer par les ignorer risque de conduire a qq chose
835 // qui pourrait ne pas etre generalisable
836 // Well, I'm expecting your code !!!
841 // Heuristic : a sequence "contains" a set of tags (called items). It looks
842 // like the last tag of a sequence (the one that terminates the sequence)
843 // has a group of 0xfffe (with a dummy length).
844 if( group == 0xfffe )
849 ElVal->SetValue("gdcm::Skipped");
853 // When the length is zero things are easy:
859 // The elements whose length is bigger than the specified upper bound
860 // are not loaded. Instead we leave a short notice of the offset of
861 // the element content and it's length.
862 if (length > MaxSizeLoadElementValue) {
864 s << "gdcm::NotLoaded.";
865 s << " Address:" << (long)ElVal->GetOffset();
866 s << " Length:" << ElVal->GetLength();
867 ElVal->SetValue(s.str());
871 // When an integer is expected, read and convert the following two or
872 // four bytes properly i.e. as an integer as opposed to a string.
874 // pour les elements de Value Multiplicity > 1
875 // on aura en fait une serie d'entiers
877 // on devrait pouvoir faire + compact (?)
879 if ( IsAnInteger(ElVal) ) {
883 if (vr == "US" || vr == "SS") {
885 NewInt = ReadInt16();
888 for (int i=1; i < nbInt; i++) {
890 NewInt = ReadInt16();
895 } else if (vr == "UL" || vr == "SL") {
897 NewInt = ReadInt32();
900 for (int i=1; i < nbInt; i++) {
902 NewInt = ReadInt32();
907 ElVal->SetValue(s.str());
911 // We need an additional byte for storing \0 that is not on disk
912 char* NewValue = (char*)malloc(length+1);
914 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
919 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
920 if ( item_read != 1 ) {
922 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
923 ElVal->SetValue("gdcm::UnRead");
926 ElVal->SetValue(NewValue);
931 * \ingroup gdcmHeader
932 * \brief Loads the element while preserving the current
933 * underlying file position indicator as opposed to
934 * to LoadElementValue that modifies it.
935 * @param ElVal Element whose value shall be loaded.
938 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
939 long PositionOnEntry = ftell(fp);
940 LoadElementValue(ElVal);
941 fseek(fp, PositionOnEntry, SEEK_SET);
945 * \ingroup gdcmHeader
950 guint16 gdcmHeader::ReadInt16(void) {
953 item_read = fread (&g, (size_t)2,(size_t)1, fp);
954 if ( item_read != 1 ) {
955 dbg.Verbose(1, "gdcmHeader::ReadInt16", " Failed to read :");
957 dbg.Verbose(1, "gdcmHeader::ReadInt16", " End of File encountered");
959 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File Error");
969 * \ingroup gdcmHeader
974 guint32 gdcmHeader::ReadInt32(void) {
977 item_read = fread (&g, (size_t)4,(size_t)1, fp);
978 if ( item_read != 1 ) {
980 dbg.Verbose(1, "gdcmHeader::ReadInt32", " Failed to read :");
982 dbg.Verbose(1, "gdcmHeader::ReadInt32", " End of File encountered");
984 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File Error");
994 * \ingroup gdcmHeader
999 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1001 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1003 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1004 "failed to Locate gdcmElValue");
1005 return (gdcmElValue*)0;
1011 * \ingroup gdcmHeader
1012 * \brief Build a new Element Value from all the low level arguments.
1013 * Check for existence of dictionary entry, and build
1014 * a default one when absent.
1015 * @param Group group of the underlying DictEntry
1016 * @param Elem element of the underlying DictEntry
1018 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1019 // Find out if the tag we encountered is in the dictionaries:
1020 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1022 NewTag = new gdcmDictEntry(Group, Elem);
1024 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1026 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1027 "failed to allocate gdcmElValue");
1028 return (gdcmElValue*)0;
1034 * \ingroup gdcmHeader
1038 int gdcmHeader::ReplaceOrCreateByNumber(string Value, guint16 Group, guint16 Elem ) {
1040 // TODO : FIXME JPRx
1042 // on (je) cree une Elvalue ne contenant pas de valeur
1043 // on l'ajoute au ElValSet
1044 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1045 // --> devrait pouvoir etre fait + simplement ???
1047 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1048 PubElValSet.Add(nvElValue);
1049 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1055 * \ingroup gdcmHeader
1059 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1061 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1062 PubElValSet.Add(nvElValue);
1064 PubElValSet.SetElValueByNumber(v, Group, Elem);
1069 * \ingroup gdcmHeader
1074 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1075 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1080 * \ingroup gdcmHeader
1081 * \brief Build a new Element Value from all the low level arguments.
1082 * Check for existence of dictionary entry, and build
1083 * a default one when absent.
1084 * @param Name Name of the underlying DictEntry
1086 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
1088 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1090 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1092 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1094 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1095 "failed to allocate gdcmElValue");
1096 return (gdcmElValue*)0;
1102 * \ingroup gdcmHeader
1103 * \brief Read the next tag but WITHOUT loading it's value
1104 * @return On succes the newly created ElValue, NULL on failure.
1106 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1109 gdcmElValue * NewElVal;
1114 if ( (g==0x7fe0) && (n==0x0010) )
1116 printf("in gdcmHeader::ReadNextElement try to read 7fe0 0010 \n");
1119 // We reached the EOF (or an error occured) and header parsing
1120 // has to be considered as finished.
1121 return (gdcmElValue *)0;
1123 NewElVal = NewElValueByNumber(g, n);
1125 FindLength(NewElVal);
1128 if (DEBUG) printf("in gdcmHeader::ReadNextElement : g %04x n %04x errno %d\n",g, n, errno);
1129 return (gdcmElValue *)0;
1131 NewElVal->SetOffset(ftell(fp));
1132 if ( (g==0x7fe0) && (n==0x0010) )
1134 printf("sortie de gdcmHeader::ReadNextElement 7fe0 0010 \n");
1139 * \ingroup gdcmHeader
1140 * \brief Apply some heuristics to predict wether the considered
1141 * element value contains/represents an integer or not.
1142 * @param ElVal The element value on which to apply the predicate.
1143 * @return The result of the heuristical predicate.
1145 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1146 guint16 group = ElVal->GetGroup();
1147 guint16 element = ElVal->GetElement();
1148 string vr = ElVal->GetVR();
1149 guint32 length = ElVal->GetLength();
1151 // When we have some semantics on the element we just read, and if we
1152 // a priori know we are dealing with an integer, then we shall be
1153 // able to swap it's element value properly.
1154 if ( element == 0 ) { // This is the group length of the group
1158 if (DEBUG) printf("Erroneous Group Length element length (%04x , %04x) : %d\n",
1159 group, element,length);
1161 dbg.Error("gdcmHeader::IsAnInteger",
1162 "Erroneous Group Length element length.");
1165 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1172 * \ingroup gdcmHeader
1173 * \brief Recover the offset (from the beginning of the file) of the pixels.
1175 size_t gdcmHeader::GetPixelOffset(void) {
1176 // If this file complies with the norm we should encounter the
1177 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1178 // the group that contains the pixel data (hence the "Pixel Data"
1179 // is found by indirection through the "Image Location").
1180 // Inside the group pointed by "Image Location" the searched element
1181 // is conventionally the element 0x0010 (when the norm is respected).
1182 // When the "Image Location" is absent we default to group 0x7fe0.
1185 string ImageLocation = GetPubElValByName("Image Location");
1186 if ( ImageLocation == "gdcm::Unfound" ) {
1189 grPixel = (guint16) atoi( ImageLocation.c_str() );
1191 if (grPixel != 0x7fe0)
1192 // This is a kludge for old dirty Philips imager.
1197 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1200 return PixelElement->GetOffset();
1206 * \ingroup gdcmHeader
1207 * \brief Searches both the public and the shadow dictionary (when they
1208 * exist) for the presence of the DictEntry with given
1209 * group and element. The public dictionary has precedence on the
1211 * @param group group of the searched DictEntry
1212 * @param element element of the searched DictEntry
1213 * @return Corresponding DictEntry when it exists, NULL otherwise.
1215 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1217 gdcmDictEntry * found = (gdcmDictEntry*)0;
1218 if (!RefPubDict && !RefShaDict) {
1219 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1220 "we SHOULD have a default dictionary");
1223 found = RefPubDict->GetTagByNumber(group, element);
1228 found = RefShaDict->GetTagByNumber(group, element);
1236 * \ingroup gdcmHeader
1237 * \brief Searches both the public and the shadow dictionary (when they
1238 * exist) for the presence of the DictEntry with given name.
1239 * The public dictionary has precedence on the shadow one.
1240 * @param Name name of the searched DictEntry
1241 * @return Corresponding DictEntry when it exists, NULL otherwise.
1243 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1244 gdcmDictEntry * found = (gdcmDictEntry*)0;
1245 if (!RefPubDict && !RefShaDict) {
1246 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1247 "we SHOULD have a default dictionary");
1250 found = RefPubDict->GetTagByName(Name);
1255 found = RefShaDict->GetTagByName(Name);
1263 * \ingroup gdcmHeader
1264 * \brief Searches within the public dictionary for element value of
1266 * @param group Group of the researched tag.
1267 * @param element Element of the researched tag.
1268 * @return Corresponding element value when it exists, and the string
1269 * "gdcm::Unfound" otherwise.
1271 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1272 return PubElValSet.GetElValueByNumber(group, element);
1276 * \ingroup gdcmHeader
1277 * \brief Searches within the public dictionary for element value
1278 * representation of a given tag.
1280 * Obtaining the VR (Value Representation) might be needed by caller
1281 * to convert the string typed content to caller's native type
1282 * (think of C++ vs Python). The VR is actually of a higher level
1283 * of semantics than just the native C++ type.
1284 * @param group Group of the researched tag.
1285 * @param element Element of the researched tag.
1286 * @return Corresponding element value representation when it exists,
1287 * and the string "gdcm::Unfound" otherwise.
1289 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1290 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1292 return "gdcm::Unfound";
1293 return elem->GetVR();
1297 * \ingroup gdcmHeader
1298 * \brief Searches within the public dictionary for element value of
1300 * @param TagName name of the researched element.
1301 * @return Corresponding element value when it exists, and the string
1302 * "gdcm::Unfound" otherwise.
1304 string gdcmHeader::GetPubElValByName(string TagName) {
1305 return PubElValSet.GetElValueByName(TagName);
1309 * \ingroup gdcmHeader
1310 * \brief Searches within the elements parsed with the public dictionary for
1311 * the element value representation of a given tag.
1313 * Obtaining the VR (Value Representation) might be needed by caller
1314 * to convert the string typed content to caller's native type
1315 * (think of C++ vs Python). The VR is actually of a higher level
1316 * of semantics than just the native C++ type.
1317 * @param TagName name of the researched element.
1318 * @return Corresponding element value representation when it exists,
1319 * and the string "gdcm::Unfound" otherwise.
1321 string gdcmHeader::GetPubElValRepByName(string TagName) {
1322 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1324 return "gdcm::Unfound";
1325 return elem->GetVR();
1329 * \ingroup gdcmHeader
1330 * \brief Searches within elements parsed with the SHADOW dictionary
1331 * for the element value of a given tag.
1332 * @param group Group of the researched tag.
1333 * @param element Element of the researched tag.
1334 * @return Corresponding element value representation when it exists,
1335 * and the string "gdcm::Unfound" otherwise.
1337 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1338 return ShaElValSet.GetElValueByNumber(group, element);
1342 * \ingroup gdcmHeader
1343 * \brief Searches within the elements parsed with the SHADOW dictionary
1344 * for the element value representation of a given tag.
1346 * Obtaining the VR (Value Representation) might be needed by caller
1347 * to convert the string typed content to caller's native type
1348 * (think of C++ vs Python). The VR is actually of a higher level
1349 * of semantics than just the native C++ type.
1350 * @param group Group of the researched tag.
1351 * @param element Element of the researched tag.
1352 * @return Corresponding element value representation when it exists,
1353 * and the string "gdcm::Unfound" otherwise.
1355 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1356 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1358 return "gdcm::Unfound";
1359 return elem->GetVR();
1363 * \ingroup gdcmHeader
1364 * \brief Searches within the elements parsed with the shadow dictionary
1365 * for an element value of given tag.
1366 * @param TagName name of the researched element.
1367 * @return Corresponding element value when it exists, and the string
1368 * "gdcm::Unfound" otherwise.
1370 string gdcmHeader::GetShaElValByName(string TagName) {
1371 return ShaElValSet.GetElValueByName(TagName);
1375 * \ingroup gdcmHeader
1376 * \brief Searches within the elements parsed with the shadow dictionary for
1377 * the element value representation of a given tag.
1379 * Obtaining the VR (Value Representation) might be needed by caller
1380 * to convert the string typed content to caller's native type
1381 * (think of C++ vs Python). The VR is actually of a higher level
1382 * of semantics than just the native C++ type.
1383 * @param TagName name of the researched element.
1384 * @return Corresponding element value representation when it exists,
1385 * and the string "gdcm::Unfound" otherwise.
1387 string gdcmHeader::GetShaElValRepByName(string TagName) {
1388 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1390 return "gdcm::Unfound";
1391 return elem->GetVR();
1395 * \ingroup gdcmHeader
1396 * \brief Searches within elements parsed with the public dictionary
1397 * and then within the elements parsed with the shadow dictionary
1398 * for the element value of a given tag.
1399 * @param group Group of the researched tag.
1400 * @param element Element of the researched tag.
1401 * @return Corresponding element value representation when it exists,
1402 * and the string "gdcm::Unfound" otherwise.
1404 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1405 string pub = GetPubElValByNumber(group, element);
1408 return GetShaElValByNumber(group, element);
1412 * \ingroup gdcmHeader
1413 * \brief Searches within elements parsed with the public dictionary
1414 * and then within the elements parsed with the shadow dictionary
1415 * for the element value representation of a given tag.
1417 * Obtaining the VR (Value Representation) might be needed by caller
1418 * to convert the string typed content to caller's native type
1419 * (think of C++ vs Python). The VR is actually of a higher level
1420 * of semantics than just the native C++ type.
1421 * @param group Group of the researched tag.
1422 * @param element Element of the researched tag.
1423 * @return Corresponding element value representation when it exists,
1424 * and the string "gdcm::Unfound" otherwise.
1426 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1427 string pub = GetPubElValRepByNumber(group, element);
1430 return GetShaElValRepByNumber(group, element);
1434 * \ingroup gdcmHeader
1435 * \brief Searches within elements parsed with the public dictionary
1436 * and then within the elements parsed with the shadow dictionary
1437 * for the element value of a given tag.
1438 * @param TagName name of the researched element.
1439 * @return Corresponding element value when it exists,
1440 * and the string "gdcm::Unfound" otherwise.
1442 string gdcmHeader::GetElValByName(string TagName) {
1443 string pub = GetPubElValByName(TagName);
1446 return GetShaElValByName(TagName);
1450 * \ingroup gdcmHeader
1451 * \brief Searches within elements parsed with the public dictionary
1452 * and then within the elements parsed with the shadow dictionary
1453 * for the element value representation of a given tag.
1455 * Obtaining the VR (Value Representation) might be needed by caller
1456 * to convert the string typed content to caller's native type
1457 * (think of C++ vs Python). The VR is actually of a higher level
1458 * of semantics than just the native C++ type.
1459 * @param TagName name of the researched element.
1460 * @return Corresponding element value representation when it exists,
1461 * and the string "gdcm::Unfound" otherwise.
1463 string gdcmHeader::GetElValRepByName(string TagName) {
1464 string pub = GetPubElValRepByName(TagName);
1467 return GetShaElValRepByName(TagName);
1471 * \ingroup gdcmHeader
1472 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1473 * through it's (group, element) and modifies it's content with
1475 * @param content new value to substitute with
1476 * @param group group of the ElVal to modify
1477 * @param element element of the ElVal to modify
1479 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1482 //TODO : homogeneiser les noms : SetPubElValByNumber qui appelle PubElValSet.SetElValueByNumber
1483 // pourquoi pas SetPubElValueByNumber ??
1486 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1490 * \ingroup gdcmHeader
1491 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1492 * through tag name and modifies it's content with the given value.
1493 * @param content new value to substitute with
1494 * @param TagName name of the tag to be modified
1496 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1497 return ( PubElValSet.SetElValueByName (content, TagName) );
1501 * \ingroup gdcmHeader
1502 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1503 * through it's (group, element) and modifies it's length with
1505 * \warning Use with extreme caution.
1506 * @param length new length to substitute with
1507 * @param group group of the ElVal to modify
1508 * @param element element of the ElVal to modify
1509 * @return 1 on success, 0 otherwise.
1512 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1514 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1518 * \ingroup gdcmHeader
1519 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1520 * through it's (group, element) and modifies it's content with
1522 * @param content new value to substitute with
1523 * @param group group of the ElVal to modify
1524 * @param element element of the ElVal to modify
1525 * @return 1 on success, 0 otherwise.
1527 int gdcmHeader::SetShaElValByNumber(string content,
1528 guint16 group, guint16 element) {
1529 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1533 * \ingroup gdcmHeader
1534 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1535 * through tag name and modifies it's content with the given value.
1536 * @param content new value to substitute with
1537 * @param ShadowTagName name of the tag to be modified
1539 int gdcmHeader::SetShaElValByName(string content, string ShadowTagName) {
1540 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1544 * \ingroup gdcmHeader
1545 * \brief Parses the header of the file but WITHOUT loading element values.
1547 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1548 gdcmElValue * newElValue = (gdcmElValue *)0;
1552 while ( (newElValue = ReadNextElement()) ) {
1553 SkipElementValue(newElValue);
1554 PubElValSet.Add(newElValue);
1561 // des que les element values sont chargees, stocker,
1562 // en une seule fois, dans des entiers
1563 // NX, NY, NZ, Bits allocated, Bits Stored, High Bit, Samples Per Pixel
1564 // (TODO : preciser les autres)
1565 // et refaire ceux des accesseurs qui renvoient les entiers correspondants
1567 // --> peut etre dangereux ?
1568 // si l'utilisateur modifie 'manuellement' l'un des paramètres
1569 // l'entier de sera pas modifié ...
1570 // (pb de la mise à jour en cas de redondance :-(
1573 * \ingroup gdcmHeader
1574 * \brief Retrieve the number of columns of image.
1575 * @return The encountered size when found, 0 by default.
1577 int gdcmHeader::GetXSize(void) {
1578 // We cannot check for "Columns" because the "Columns" tag is present
1579 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1580 string StrSize = GetPubElValByNumber(0x0028,0x0011);
1581 if (StrSize == "gdcm::Unfound")
1583 return atoi(StrSize.c_str());
1587 * \ingroup gdcmHeader
1588 * \brief Retrieve the number of lines of image.
1589 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1590 * @return The encountered size when found, 1 by default.
1592 int gdcmHeader::GetYSize(void) {
1593 // We cannot check for "Rows" because the "Rows" tag is present
1594 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1595 string StrSize = GetPubElValByNumber(0x0028,0x0010);
1596 if (StrSize != "gdcm::Unfound")
1597 return atoi(StrSize.c_str());
1601 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1602 // hence be a signal (1d image). So we default to 1:
1607 * \ingroup gdcmHeader
1608 * \brief Retrieve the number of planes of volume or the number
1609 * of frames of a multiframe.
1610 * \warning When present we consider the "Number of Frames" as the third
1611 * dimension. When absent we consider the third dimension as
1612 * being the "Planes" tag content.
1613 * @return The encountered size when found, 1 by default.
1615 int gdcmHeader::GetZSize(void) {
1616 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1617 // as the third dimension.
1618 string StrSize = GetPubElValByNumber(0x0028,0x0008);
1619 if (StrSize != "gdcm::Unfound")
1620 return atoi(StrSize.c_str());
1622 // We then consider the "Planes" entry as the third dimension [we
1623 // cannot retrieve by name since "Planes tag is present both in
1624 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1625 StrSize = GetPubElValByNumber(0x0028,0x0012);
1626 if (StrSize != "gdcm::Unfound")
1627 return atoi(StrSize.c_str());
1632 * \ingroup gdcmHeader
1633 * \brief Retrieve the number of Bits Stored
1634 * (as opposite to number of Bits Allocated)
1636 * @return The encountered number of Bits Stored, 0 by default.
1638 int gdcmHeader::GetBitsStored(void) {
1639 string StrSize = GetPubElValByNumber(0x0028,0x0101);
1640 if (StrSize == "gdcm::Unfound")
1642 return atoi(StrSize.c_str());
1646 * \ingroup gdcmHeader
1647 * \brief Retrieve the number of Samples Per Pixel
1648 * (1 : gray level, 3 : RGB)
1650 * @return The encountered number of Samples Per Pixel, 1 by default.
1652 int gdcmHeader::GetSamplesPerPixel(void) {
1653 string StrSize = GetPubElValByNumber(0x0028,0x0002);
1654 if (StrSize == "gdcm::Unfound")
1655 return 1; // Well, it's supposed to be mandatory ...
1656 return atoi(StrSize.c_str());
1660 * \ingroup gdcmHeader
1661 * \brief Return the size (in bytes) of a single pixel of data.
1662 * @return The size in bytes of a single pixel of data.
1665 int gdcmHeader::GetPixelSize(void) {
1666 string PixelType = GetPixelType();
1667 if (PixelType == "8U" || PixelType == "8S")
1669 if (PixelType == "16U" || PixelType == "16S")
1671 if (PixelType == "32U" || PixelType == "32S")
1673 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1678 * \ingroup gdcmHeader
1679 * \brief Build the Pixel Type of the image.
1680 * Possible values are:
1681 * - 8U unsigned 8 bit,
1682 * - 8S signed 8 bit,
1683 * - 16U unsigned 16 bit,
1684 * - 16S signed 16 bit,
1685 * - 32U unsigned 32 bit,
1686 * - 32S signed 32 bit,
1687 * \warning 12 bit images appear as 16 bit.
1690 string gdcmHeader::GetPixelType(void) {
1692 BitsAlloc = GetElValByName("Bits Allocated");
1693 if (BitsAlloc == "gdcm::Unfound") {
1694 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1695 BitsAlloc = string("16");
1697 if (BitsAlloc == "12")
1698 BitsAlloc = string("16");
1701 Signed = GetElValByName("Pixel Representation");
1702 if (Signed == "gdcm::Unfound") {
1703 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1704 BitsAlloc = string("0");
1707 Signed = string("U");
1709 Signed = string("S");
1711 return( BitsAlloc + Signed);
1716 * \ingroup gdcmHeader
1717 * \brief This predicate, based on hopefully reasonnable heuristics,
1718 * decides whether or not the current gdcmHeader was properly parsed
1719 * and contains the mandatory information for being considered as
1720 * a well formed and usable image.
1721 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1724 bool gdcmHeader::IsReadable(void) {
1725 if ( GetElValByName("Image Dimensions") != "gdcm::Unfound"
1726 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1729 if ( GetElValByName("Bits Allocated") == "gdcm::Unfound" )
1731 if ( GetElValByName("Bits Stored") == "gdcm::Unfound" )
1733 if ( GetElValByName("High Bit") == "gdcm::Unfound" )
1735 if ( GetElValByName("Pixel Representation") == "gdcm::Unfound" )
1741 * \ingroup gdcmHeader
1742 * \brief Small utility function that creates a new manually crafted
1743 * (as opposed as read from the file) gdcmElValue with user
1744 * specified name and adds it to the public tag hash table.
1745 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1746 * @param NewTagName The name to be given to this new tag.
1747 * @param VR The Value Representation to be given to this new tag.
1748 * @ return The newly hand crafted Element Value.
1750 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1751 gdcmElValue* NewElVal = (gdcmElValue*)0;
1752 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1753 guint32 FreeElem = 0;
1754 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1756 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1757 if (FreeElem == UINT32_MAX) {
1758 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1759 "Group 0xffff in Public Dict is full");
1760 return (gdcmElValue*)0;
1762 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1763 VR, "GDCM", NewTagName);
1764 NewElVal = new gdcmElValue(NewEntry);
1765 PubElValSet.Add(NewElVal);
1770 * \ingroup gdcmHeader
1771 * \brief Loads the element values of all the elements present in the
1772 * public tag based hash table.
1774 void gdcmHeader::LoadElements(void) {
1776 TagElValueHT ht = PubElValSet.GetTagHt();
1777 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1778 LoadElementValue(tag->second);
1783 * \ingroup gdcmHeader
1787 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1788 PubElValSet.Print(os);
1792 * \ingroup gdcmHeader
1796 void gdcmHeader::PrintPubDict(std::ostream & os) {
1797 RefPubDict->Print(os);
1801 * \ingroup gdcmHeader
1806 int gdcmHeader::Write(FILE * fp, FileType type) {
1807 return PubElValSet.Write(fp, type);
1811 * \ingroup gdcmHeader
1815 float gdcmHeader::GetXSpacing(void) {
1816 float xspacing, yspacing;
1817 string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1819 if (StrSpacing == "gdcm::Unfound") {
1820 dbg.Verbose(0, "gdcmHeader::GetXSpacing: unfound Pixel Spacing");
1823 if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1830 * \ingroup gdcmHeader
1834 float gdcmHeader::GetYSpacing(void) {
1835 float xspacing, yspacing;
1836 string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1838 if (StrSpacing == "gdcm::Unfound") {
1839 dbg.Verbose(0, "gdcmHeader::GetYSpacing: unfound Pixel Spacing");
1843 if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1848 dbg.Verbose(0, "gdcmHeader::GetYSpacing: gdcmData/CT-MONO2-8-abdo.dcm problem");
1849 // seems to be a bug in the header ...
1850 sscanf( StrSpacing.c_str(), "%f\\0\\%f", &xspacing, &yspacing);
1857 * \ingroup gdcmHeader
1861 float gdcmHeader::GetZSpacing(void) {
1862 // TODO : translate into English
1863 // Spacing Between Slices : distance entre le milieu de chaque coupe
1864 // Les coupes peuvent etre :
1865 // jointives (Spacing between Slices = Slice Thickness)
1866 // chevauchantes (Spacing between Slices < Slice Thickness)
1867 // disjointes (Spacing between Slices > Slice Thickness)
1868 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
1869 // ca interesse le physicien de l'IRM, pas le visualisateur de volumes ...
1870 // Si le Spacing Between Slices est absent,
1871 // on suppose que les coupes sont jointives
1873 string StrSpacingBSlices = GetPubElValByNumber(0x0018,0x0088);
1875 if (StrSpacingBSlices == "gdcm::Unfound") {
1876 dbg.Verbose(0, "gdcmHeader::GetZSpacing: unfound StrSpacingBSlices");
1877 string StrSliceThickness = GetPubElValByNumber(0x0018,0x0050);
1878 if (StrSliceThickness == "gdcm::Unfound")
1881 // if no 'Spacing Between Slices' is found,
1882 // we assume slices join together
1883 // (no overlapping, no interslice gap)
1884 // if they don't, we're fucked up
1885 return atof(StrSliceThickness.c_str());
1887 return atof(StrSpacingBSlices.c_str());
1892 // Image Position Patient (0020,0032):
1893 // If not found (ACR_NEMA) we try Image Position (0020,0030)
1894 // If not found (ACR-NEMA), we consider Slice Location (20,1041)
1895 // or Location (0020,0050)
1896 // as the Z coordinate,
1897 // 0. for all the coordinates if nothing is found
1898 // TODO : find a way to inform the caller nothing was found
1899 // TODO : How to tell the caller a wrong number of values was found?
1901 * \ingroup gdcmHeader
1905 float gdcmHeader::GetXImagePosition(void) {
1906 float xImPos, yImPos, zImPos;
1907 // 0020,0032 : Image Position Patient
1908 // 0020,0030 : Image Position (RET)
1909 // 0020,1041 : Slice Location
1911 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1913 if (StrImPos == "gdcm::Unfound") {
1914 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Image Position Patient (0020,0032)");
1915 StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1916 if (StrImPos == "gdcm::Unfound") {
1917 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Image Position (RET) (0020,0030)");
1918 string StrSliceLoc = GetPubElValByNumber(0x0020,0x1041); // for *very* old ACR-NEMA images
1919 if (StrSliceLoc == "gdcm::Unfound") {
1920 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Slice Location (0020,1041)");
1921 // How to tell the caller nothing was found?
1926 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1927 // How to tell the caller a wrong number of values was found?
1934 * \ingroup gdcmHeader
1938 float gdcmHeader::GetYImagePosition(void) {
1939 float xImPos, yImPos, zImPos;
1940 // 0020,0032 : Image Position Patient
1941 // 0020,1041 : Slice Location
1942 // 0020,0050 : Location
1943 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1945 if (StrImPos == "gdcm::Unfound") {
1946 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position Patient (0020,0032)");
1947 StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1948 if (StrImPos == "gdcm::Unfound") {
1949 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position (RET) (0020,0030)");
1950 string StrSliceLoc = GetPubElValByNumber(0x0020,0x1041); // for *very* old ACR-NEMA images
1951 if (StrSliceLoc == "gdcm::Unfound") {
1952 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location (0020,1041)");
1953 // How to tell the caller nothing was found?
1958 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1959 // How to tell the caller a wrong number of values was found?
1965 * \ingroup gdcmHeader
1969 float gdcmHeader::GetZImagePosition(void) {
1970 float xImPos, yImPos, zImPos;
1971 // 0020,0032 : Image Position Patient
1972 // 0020,1041 : Slice Location
1973 // 0020,0050 : Location
1975 // TODO : How to tell the caller nothing was found?
1976 // TODO : How to tell the caller a wrong number of values was found?
1978 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1979 if (StrImPos != "gdcm::Unfound") {
1980 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3) {
1981 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Image Position Patient (0020,0032)");
1982 return 0.; // bug in the element 0x0020,0x0032
1988 StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1989 if (StrImPos != "gdcm::Unfound") {
1990 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3) {
1991 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Image Position (RET) (0020,0030)");
1992 return 0.; // bug in the element 0x0020,0x0032
1998 string StrSliceLocation = GetPubElValByNumber(0x0020,0x1041);// for *very* old ACR-NEMA images
1999 if (StrSliceLocation != "gdcm::Unfound") {
2000 if( sscanf( StrSliceLocation.c_str(), "%f", &zImPos) !=1) {
2001 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Slice Location (0020,1041)");
2002 return 0.; // bug in the element 0x0020,0x1041
2007 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: unfound Slice Location (0020,1041)");
2009 string StrLocation = GetPubElValByNumber(0x0020,0x0050);
2010 if (StrLocation != "gdcm::Unfound") {
2011 if( sscanf( StrLocation.c_str(), "%f", &zImPos) !=1) {
2012 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Location (0020,0050)");
2013 return 0.; // bug in the element 0x0020,0x0050
2018 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
2020 return 0.; // Hopeless