2 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.75 2003/07/01 17:22:44 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.
304 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
305 if (filetype != ExplicitVR)
311 char msg[100]; // for sprintf. Sorry
313 long PositionOnEntry = ftell(fp);
314 // Warning: we believe this is explicit VR (Value Representation) because
315 // we used a heuristic that found "UL" in the first tag. Alas this
316 // doesn't guarantee that all the tags will be in explicit VR. In some
317 // cases (see e-film filtered files) one finds implicit VR tags mixed
318 // within an explicit VR file. Hence we make sure the present tag
319 // is in explicit VR and try to fix things if it happens not to be
321 bool RealExplicit = true;
323 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
327 // Assume we are reading a falsely explicit VR file i.e. we reached
328 // a tag where we expect reading a VR but are in fact we read the
329 // first to bytes of the length. Then we will interogate (through find)
330 // the dicom_vr dictionary with oddities like "\004\0" which crashes
331 // both GCC and VC++ implementations of the STL map. Hence when the
332 // expected VR read happens to be non-ascii characters we consider
333 // we hit falsely explicit VR tag.
335 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
336 RealExplicit = false;
338 // CLEANME searching the dicom_vr at each occurence is expensive.
339 // PostPone this test in an optional integrity check at the end
340 // of parsing or only in debug mode.
341 if ( RealExplicit && !dicom_vr->Count(vr) )
344 if ( RealExplicit ) {
345 if ( ElVal->IsVrUnknown() ) {
346 // When not a dictionary entry, we can safely overwrite the vr.
350 if ( ElVal->GetVR() == vr ) {
351 // The vr we just read and the dictionary agree. Nothing to do.
354 // The vr present in the file and the dictionary disagree. We assume
355 // the file writer knew best and use the vr of the file. Since it would
356 // be unwise to overwrite the vr of a dictionary (since it would
357 // compromise it's next user), we need to clone the actual DictEntry
358 // and change the vr for the read one.
359 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
364 ElVal->SetDictEntry(NewTag);
368 // We thought this was explicit VR, but we end up with an
369 // implicit VR tag. Let's backtrack.
371 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", ElVal->GetGroup(),ElVal->GetElement());
372 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
374 fseek(fp, PositionOnEntry, SEEK_SET);
375 // When this element is known in the dictionary we shall use, e.g. for
376 // the semantics (see the usage of IsAnInteger), the vr proposed by the
377 // dictionary entry. Still we have to flag the element as implicit since
378 // we know now our assumption on expliciteness is not furfilled.
380 if ( ElVal->IsVrUnknown() )
381 ElVal->SetVR("Implicit");
382 ElVal->SetImplicitVr();
386 * \ingroup gdcmHeader
387 * \brief Determines if the Transfer Syntax was allready encountered
388 * and if it corresponds to a ImplicitVRLittleEndian one.
390 * @return True when ImplicitVRLittleEndian found. False in all other cases.
392 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(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" )
404 * \ingroup gdcmHeader
405 * \brief Determines if the Transfer Syntax was allready encountered
406 * and if it corresponds to a ExplicitVRLittleEndian one.
408 * @return True when ExplicitVRLittleEndian found. False in all other cases.
410 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(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.1" )
422 * \ingroup gdcmHeader
423 * \brief Determines if the Transfer Syntax was allready encountered
424 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
426 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
428 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(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.1.99" )
440 * \ingroup gdcmHeader
441 * \brief Determines if the Transfer Syntax was allready encountered
442 * and if it corresponds to a Explicit VR Big Endian one.
444 * @return True when big endian found. False in all other cases.
446 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
447 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
450 LoadElementValueSafe(Element);
451 string Transfer = Element->GetValue();
452 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
458 * \ingroup gdcmHeader
459 * \brief Determines if the Transfer Syntax was allready encountered
460 * and if it corresponds to a JPEGBaseLineProcess1 one.
462 * @return True when JPEGBaseLineProcess1found. False in all other cases.
464 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
465 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
468 LoadElementValueSafe(Element);
469 string Transfer = Element->GetValue();
470 if ( Transfer == "1.2.840.10008.1.2.4.50" )
476 * \ingroup gdcmHeader
481 bool gdcmHeader::IsJPEGLossless(void) {
482 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
483 // faire qq chose d'intelligent a la place de ça
486 LoadElementValueSafe(Element);
487 const char * Transfert = Element->GetValue().c_str();
488 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
489 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
495 * \ingroup gdcmHeader
496 * \brief Determines if the Transfer Syntax was allready encountered
497 * and if it corresponds to a JPEGExtendedProcess2-4 one.
499 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
501 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
502 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
505 LoadElementValueSafe(Element);
506 string Transfer = Element->GetValue();
507 if ( Transfer == "1.2.840.10008.1.2.4.51" )
513 * \ingroup gdcmHeader
514 * \brief Determines if the Transfer Syntax was allready encountered
515 * and if it corresponds to a JPEGExtendeProcess3-5 one.
517 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
519 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
520 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
523 LoadElementValueSafe(Element);
524 string Transfer = Element->GetValue();
525 if ( Transfer == "1.2.840.10008.1.2.4.52" )
531 * \ingroup gdcmHeader
532 * \brief Determines if the Transfer Syntax was allready encountered
533 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
535 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
538 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
539 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
542 LoadElementValueSafe(Element);
543 string Transfer = Element->GetValue();
544 if ( Transfer == "1.2.840.10008.1.2.4.53" )
550 * \ingroup gdcmHeader
551 * \brief Predicate for dicom version 3 file.
552 * @return True when the file is a dicom version 3.
554 bool gdcmHeader::IsDicomV3(void) {
555 if ( (filetype == ExplicitVR)
556 || (filetype == ImplicitVR) )
562 * \ingroup gdcmHeader
563 * \brief When the length of an element value is obviously wrong (because
564 * the parser went Jabberwocky) one can hope improving things by
565 * applying this heuristic.
567 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
568 if ( FoundLength == 0xffffffff)
570 ElVal->SetLength(FoundLength);
574 * \ingroup gdcmHeader
579 guint32 gdcmHeader::FindLengthOB(void) {
580 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
583 long PositionOnEntry = ftell(fp);
584 bool FoundSequenceDelimiter = false;
585 guint32 TotalLength = 0;
588 while ( ! FoundSequenceDelimiter) {
592 if (DEBUG) printf ("dans FindLengthOB (%04x,%04x)\n",g,n);
594 if (DEBUG) printf("en %d o(%o) x(%x)\n",l,l,l);
598 TotalLength += 4; // We even have to decount the group and element
600 if ( g != 0xfffe && g!=0xb00c ) /*for bogus headerJPR */ {
601 char msg[100]; // for sprintf. Sorry
602 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
603 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
605 if (DEBUG) printf("en %d o(%o) x(%x)\n",l,l,l);
610 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header JPR */
611 FoundSequenceDelimiter = true;
612 else if ( n != 0xe000 ){
613 char msg[100]; // for sprintf. Sorry
614 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
615 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
616 if (DEBUG) printf("wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
620 ItemLength = ReadInt32();
621 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
622 // the ItemLength with ReadInt32
624 if (DEBUG) printf("TotalLength %d\n",TotalLength);
625 SkipBytes(ItemLength);
627 fseek(fp, PositionOnEntry, SEEK_SET);
632 * \ingroup gdcmHeader
637 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
638 guint16 element = ElVal->GetElement();
639 guint16 group = ElVal->GetGroup(); // JPR a virer
640 string vr = ElVal->GetVR();
642 if( (element == 0x0010) && (group == 0x7fe0) ) {// JPR
645 dbg.Verbose(2, "gdcmHeader::FindLength: ", // JPR
646 "on est sur 7fe0 0010");
649 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
650 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
652 // The following reserved two bytes (see PS 3.5-2001, section
653 // 7.1.2 Data element structure with explicit vr p27) must be
654 // skipped before proceeding on reading the length on 4 bytes.
655 fseek(fp, 2L, SEEK_CUR);
657 guint32 length32 = ReadInt32();
658 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
659 ElVal->SetLength(FindLengthOB());
662 FixFoundLength(ElVal, length32);
666 // Length is encoded on 2 bytes.
667 length16 = ReadInt16();
669 // We can tell the current file is encoded in big endian (like
670 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
671 // and it's value is the one of the encoding of a big endian file.
672 // In order to deal with such big endian encoded files, we have
673 // (at least) two strategies:
674 // * when we load the "Transfer Syntax" tag with value of big endian
675 // encoding, we raise the proper flags. Then we wait for the end
676 // of the META group (0x0002) among which is "Transfer Syntax",
677 // before switching the swap code to big endian. We have to postpone
678 // the switching of the swap code since the META group is fully encoded
679 // in little endian, and big endian coding only starts at the next
680 // group. The corresponding code can be hard to analyse and adds
681 // many additional unnecessary tests for regular tags.
682 // * the second strategy consists in waiting for trouble, that shall
683 // appear when we find the first group with big endian encoding. This
684 // is easy to detect since the length of a "Group Length" tag (the
685 // ones with zero as element number) has to be of 4 (0x0004). When we
686 // encouter 1024 (0x0400) chances are the encoding changed and we
687 // found a group with big endian encoding.
688 // We shall use this second strategy. In order to make sure that we
689 // can interpret the presence of an apparently big endian encoded
690 // length of a "Group Length" without committing a big mistake, we
691 // add an additional check: we look in the allready parsed elements
692 // for the presence of a "Transfer Syntax" whose value has to be "big
693 // endian encoding". When this is the case, chances are we have got our
694 // hands on a big endian encoded file: we switch the swap code to
695 // big endian and proceed...
696 if ( (element == 0x0000) && (length16 == 0x0400) ) {
697 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
698 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
703 SwitchSwapToBigEndian();
704 // Restore the unproperly loaded values i.e. the group, the element
705 // and the dictionary entry depending on them.
706 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
707 guint16 CorrectElem = SwapShort(ElVal->GetElement());
708 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
711 // This correct tag is not in the dictionary. Create a new one.
712 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
714 // FIXME this can create a memory leaks on the old entry that be
715 // left unreferenced.
716 ElVal->SetDictEntry(NewTag);
719 // Heuristic: well some files are really ill-formed.
720 if ( length16 == 0xffff) {
722 dbg.Verbose(0, "gdcmHeader::FindLength",
723 "Erroneous element length fixed.");
725 FixFoundLength(ElVal, (guint32)length16);
729 // Either implicit VR or a non DICOM conformal (see not below) explicit
730 // VR that ommited the VR of (at least) this element. Farts happen.
731 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
732 // on Data elements "Implicit and Explicit VR Data Elements shall
733 // not coexist in a Data Set and Data Sets nested within it".]
734 // Length is on 4 bytes.
735 FixFoundLength(ElVal, ReadInt32());
739 * \ingroup gdcmHeader
740 * \brief Swaps back the bytes of 4-byte long integer accordingly to
743 * @return The suggested integer.
745 guint32 gdcmHeader::SwapLong(guint32 a) {
750 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
751 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
755 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
759 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
762 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
769 * \ingroup gdcmHeader
770 * \brief Swaps the bytes so they agree with the processor order
771 * @return The properly swaped 16 bits integer.
773 guint16 gdcmHeader::SwapShort(guint16 a) {
774 if ( (sw==4321) || (sw==2143) )
775 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
780 * \ingroup gdcmHeader
785 void gdcmHeader::SkipBytes(guint32 NBytes) {
786 //FIXME don't dump the returned value
787 (void)fseek(fp, (long)NBytes, SEEK_CUR);
791 * \ingroup gdcmHeader
796 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
797 SkipBytes(ElVal->GetLength());
801 * \ingroup gdcmHeader
806 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
809 if ((guint32)NewSize >= (guint32)0xffffffff) {
810 MaxSizeLoadElementValue = 0xffffffff;
813 MaxSizeLoadElementValue = NewSize;
817 * \ingroup gdcmHeader
818 * \brief Loads the element content if it's length is not bigger
819 * than the value specified with
820 * gdcmHeader::SetMaxSizeLoadElementValue()
822 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
824 guint16 group = ElVal->GetGroup();
825 string vr = ElVal->GetVR();
826 guint32 length = ElVal->GetLength();
827 bool SkipLoad = false;
829 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
831 // FIXME Sequences not treated yet !
833 // Ne faudrait-il pas au contraire trouver immediatement
834 // une maniere 'propre' de traiter les sequences (vr = SQ)
835 // car commencer par les ignorer risque de conduire a qq chose
836 // qui pourrait ne pas etre generalisable
837 // Well, I'm expecting your code !!!
842 // Heuristic : a sequence "contains" a set of tags (called items). It looks
843 // like the last tag of a sequence (the one that terminates the sequence)
844 // has a group of 0xfffe (with a dummy length).
845 if( group == 0xfffe )
850 ElVal->SetValue("gdcm::Skipped");
854 // When the length is zero things are easy:
860 // The elements whose length is bigger than the specified upper bound
861 // are not loaded. Instead we leave a short notice of the offset of
862 // the element content and it's length.
863 if (length > MaxSizeLoadElementValue) {
865 s << "gdcm::NotLoaded.";
866 s << " Address:" << (long)ElVal->GetOffset();
867 s << " Length:" << ElVal->GetLength();
868 ElVal->SetValue(s.str());
872 // When an integer is expected, read and convert the following two or
873 // four bytes properly i.e. as an integer as opposed to a string.
875 // pour les elements de Value Multiplicity > 1
876 // 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
1040 int gdcmHeader::ReplaceOrCreateByNumber(string Value, guint16 Group, guint16 Elem ) {
1042 // TODO : FIXME JPRx
1044 // on (je) cree une Elvalue ne contenant pas de valeur
1045 // on l'ajoute au ElValSet
1046 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1047 // --> devrait pouvoir etre fait + simplement ???
1049 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1050 PubElValSet.Add(nvElValue);
1051 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1057 * \ingroup gdcmHeader
1063 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1065 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1066 PubElValSet.Add(nvElValue);
1068 PubElValSet.SetElValueByNumber(v, Group, Elem);
1073 * \ingroup gdcmHeader
1079 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1080 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1085 * \ingroup gdcmHeader
1086 * \brief Build a new Element Value from all the low level arguments.
1087 * Check for existence of dictionary entry, and build
1088 * a default one when absent.
1089 * @param Name Name of the underlying DictEntry
1091 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
1093 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1095 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1097 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1099 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1100 "failed to allocate gdcmElValue");
1101 return (gdcmElValue*)0;
1107 * \ingroup gdcmHeader
1108 * \brief Read the next tag but WITHOUT loading it's value
1109 * @return On succes the newly created ElValue, NULL on failure.
1111 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1114 gdcmElValue * NewElVal;
1119 if ( (g==0x7fe0) && (n==0x0010) )
1121 printf("in gdcmHeader::ReadNextElement try to read 7fe0 0010 \n");
1124 // We reached the EOF (or an error occured) and header parsing
1125 // has to be considered as finished.
1126 return (gdcmElValue *)0;
1128 NewElVal = NewElValueByNumber(g, n);
1130 FindLength(NewElVal);
1133 if (DEBUG) printf("in gdcmHeader::ReadNextElement : g %04x n %04x errno %d\n",g, n, errno);
1134 return (gdcmElValue *)0;
1136 NewElVal->SetOffset(ftell(fp));
1137 if ( (g==0x7fe0) && (n==0x0010) )
1139 printf("sortie de gdcmHeader::ReadNextElement 7fe0 0010 \n");
1144 * \ingroup gdcmHeader
1145 * \brief Apply some heuristics to predict wether the considered
1146 * element value contains/represents an integer or not.
1147 * @param ElVal The element value on which to apply the predicate.
1148 * @return The result of the heuristical predicate.
1150 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1151 guint16 group = ElVal->GetGroup();
1152 guint16 element = ElVal->GetElement();
1153 string vr = ElVal->GetVR();
1154 guint32 length = ElVal->GetLength();
1156 // When we have some semantics on the element we just read, and if we
1157 // a priori know we are dealing with an integer, then we shall be
1158 // able to swap it's element value properly.
1159 if ( element == 0 ) { // This is the group length of the group
1163 if (DEBUG) printf("Erroneous Group Length element length (%04x , %04x) : %d\n",
1164 group, element,length);
1166 dbg.Error("gdcmHeader::IsAnInteger",
1167 "Erroneous Group Length element length.");
1170 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1177 * \ingroup gdcmHeader
1178 * \brief Recover the offset (from the beginning of the file) of the pixels.
1180 size_t gdcmHeader::GetPixelOffset(void) {
1181 // If this file complies with the norm we should encounter the
1182 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1183 // the group that contains the pixel data (hence the "Pixel Data"
1184 // is found by indirection through the "Image Location").
1185 // Inside the group pointed by "Image Location" the searched element
1186 // is conventionally the element 0x0010 (when the norm is respected).
1187 // When the "Image Location" is absent we default to group 0x7fe0.
1190 string ImageLocation = GetPubElValByName("Image Location");
1191 if ( ImageLocation == "gdcm::Unfound" ) {
1194 grPixel = (guint16) atoi( ImageLocation.c_str() );
1196 if (grPixel != 0x7fe0)
1197 // This is a kludge for old dirty Philips imager.
1202 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1205 return PixelElement->GetOffset();
1211 * \ingroup gdcmHeader
1212 * \brief Searches both the public and the shadow dictionary (when they
1213 * exist) for the presence of the DictEntry with given
1214 * group and element. The public dictionary has precedence on the
1216 * @param group group of the searched DictEntry
1217 * @param element element of the searched DictEntry
1218 * @return Corresponding DictEntry when it exists, NULL otherwise.
1220 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1222 gdcmDictEntry * found = (gdcmDictEntry*)0;
1223 if (!RefPubDict && !RefShaDict) {
1224 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1225 "we SHOULD have a default dictionary");
1228 found = RefPubDict->GetTagByNumber(group, element);
1233 found = RefShaDict->GetTagByNumber(group, element);
1241 * \ingroup gdcmHeader
1242 * \brief Searches both the public and the shadow dictionary (when they
1243 * exist) for the presence of the DictEntry with given name.
1244 * The public dictionary has precedence on the shadow one.
1245 * @param Name name of the searched DictEntry
1246 * @return Corresponding DictEntry when it exists, NULL otherwise.
1248 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1249 gdcmDictEntry * found = (gdcmDictEntry*)0;
1250 if (!RefPubDict && !RefShaDict) {
1251 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1252 "we SHOULD have a default dictionary");
1255 found = RefPubDict->GetTagByName(Name);
1260 found = RefShaDict->GetTagByName(Name);
1268 * \ingroup gdcmHeader
1269 * \brief Searches within the public dictionary for element value of
1271 * @param group Group of the researched tag.
1272 * @param element Element of the researched tag.
1273 * @return Corresponding element value when it exists, and the string
1274 * "gdcm::Unfound" otherwise.
1276 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1277 return PubElValSet.GetElValueByNumber(group, element);
1281 * \ingroup gdcmHeader
1282 * \brief Searches within the public dictionary for element value
1283 * representation of a given tag.
1285 * Obtaining the VR (Value Representation) might be needed by caller
1286 * to convert the string typed content to caller's native type
1287 * (think of C++ vs Python). The VR is actually of a higher level
1288 * of semantics than just the native C++ type.
1289 * @param group Group of the researched tag.
1290 * @param element Element of the researched tag.
1291 * @return Corresponding element value representation when it exists,
1292 * and the string "gdcm::Unfound" otherwise.
1294 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1295 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1297 return "gdcm::Unfound";
1298 return elem->GetVR();
1302 * \ingroup gdcmHeader
1303 * \brief Searches within the public dictionary for element value of
1305 * @param TagName name of the researched element.
1306 * @return Corresponding element value when it exists, and the string
1307 * "gdcm::Unfound" otherwise.
1309 string gdcmHeader::GetPubElValByName(string TagName) {
1310 return PubElValSet.GetElValueByName(TagName);
1314 * \ingroup gdcmHeader
1315 * \brief Searches within the elements parsed with the public dictionary for
1316 * the element value representation of a given tag.
1318 * Obtaining the VR (Value Representation) might be needed by caller
1319 * to convert the string typed content to caller's native type
1320 * (think of C++ vs Python). The VR is actually of a higher level
1321 * of semantics than just the native C++ type.
1322 * @param TagName name of the researched element.
1323 * @return Corresponding element value representation when it exists,
1324 * and the string "gdcm::Unfound" otherwise.
1326 string gdcmHeader::GetPubElValRepByName(string TagName) {
1327 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1329 return "gdcm::Unfound";
1330 return elem->GetVR();
1334 * \ingroup gdcmHeader
1335 * \brief Searches within elements parsed with the SHADOW dictionary
1336 * for the element value of a given tag.
1337 * @param group Group of the researched tag.
1338 * @param element Element of the researched tag.
1339 * @return Corresponding element value representation when it exists,
1340 * and the string "gdcm::Unfound" otherwise.
1342 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1343 return ShaElValSet.GetElValueByNumber(group, element);
1347 * \ingroup gdcmHeader
1348 * \brief Searches within the elements parsed with the SHADOW dictionary
1349 * for the element value representation of a given tag.
1351 * Obtaining the VR (Value Representation) might be needed by caller
1352 * to convert the string typed content to caller's native type
1353 * (think of C++ vs Python). The VR is actually of a higher level
1354 * of semantics than just the native C++ type.
1355 * @param group Group of the researched tag.
1356 * @param element Element of the researched tag.
1357 * @return Corresponding element value representation when it exists,
1358 * and the string "gdcm::Unfound" otherwise.
1360 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1361 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1363 return "gdcm::Unfound";
1364 return elem->GetVR();
1368 * \ingroup gdcmHeader
1369 * \brief Searches within the elements parsed with the shadow dictionary
1370 * for an element value of given tag.
1371 * @param TagName name of the researched element.
1372 * @return Corresponding element value when it exists, and the string
1373 * "gdcm::Unfound" otherwise.
1375 string gdcmHeader::GetShaElValByName(string TagName) {
1376 return ShaElValSet.GetElValueByName(TagName);
1380 * \ingroup gdcmHeader
1381 * \brief Searches within the elements parsed with the shadow dictionary for
1382 * the element value representation of a given tag.
1384 * Obtaining the VR (Value Representation) might be needed by caller
1385 * to convert the string typed content to caller's native type
1386 * (think of C++ vs Python). The VR is actually of a higher level
1387 * of semantics than just the native C++ type.
1388 * @param TagName name of the researched element.
1389 * @return Corresponding element value representation when it exists,
1390 * and the string "gdcm::Unfound" otherwise.
1392 string gdcmHeader::GetShaElValRepByName(string TagName) {
1393 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1395 return "gdcm::Unfound";
1396 return elem->GetVR();
1400 * \ingroup gdcmHeader
1401 * \brief Searches within elements parsed with the public dictionary
1402 * and then within the elements parsed with the shadow dictionary
1403 * for the element value of a given tag.
1404 * @param group Group of the researched tag.
1405 * @param element Element of the researched tag.
1406 * @return Corresponding element value representation when it exists,
1407 * and the string "gdcm::Unfound" otherwise.
1409 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1410 string pub = GetPubElValByNumber(group, element);
1413 return GetShaElValByNumber(group, element);
1417 * \ingroup gdcmHeader
1418 * \brief Searches within elements parsed with the public dictionary
1419 * and then within the elements parsed with the shadow dictionary
1420 * for the element value representation of a given tag.
1422 * Obtaining the VR (Value Representation) might be needed by caller
1423 * to convert the string typed content to caller's native type
1424 * (think of C++ vs Python). The VR is actually of a higher level
1425 * of semantics than just the native C++ type.
1426 * @param group Group of the researched tag.
1427 * @param element Element of the researched tag.
1428 * @return Corresponding element value representation when it exists,
1429 * and the string "gdcm::Unfound" otherwise.
1431 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1432 string pub = GetPubElValRepByNumber(group, element);
1435 return GetShaElValRepByNumber(group, element);
1439 * \ingroup gdcmHeader
1440 * \brief Searches within elements parsed with the public dictionary
1441 * and then within the elements parsed with the shadow dictionary
1442 * for the element value of a given tag.
1443 * @param TagName name of the researched element.
1444 * @return Corresponding element value when it exists,
1445 * and the string "gdcm::Unfound" otherwise.
1447 string gdcmHeader::GetElValByName(string TagName) {
1448 string pub = GetPubElValByName(TagName);
1451 return GetShaElValByName(TagName);
1455 * \ingroup gdcmHeader
1456 * \brief Searches within elements parsed with the public dictionary
1457 * and then within the elements parsed with the shadow dictionary
1458 * for the element value representation of a given tag.
1460 * Obtaining the VR (Value Representation) might be needed by caller
1461 * to convert the string typed content to caller's native type
1462 * (think of C++ vs Python). The VR is actually of a higher level
1463 * of semantics than just the native C++ type.
1464 * @param TagName name of the researched element.
1465 * @return Corresponding element value representation when it exists,
1466 * and the string "gdcm::Unfound" otherwise.
1468 string gdcmHeader::GetElValRepByName(string TagName) {
1469 string pub = GetPubElValRepByName(TagName);
1472 return GetShaElValRepByName(TagName);
1476 * \ingroup gdcmHeader
1477 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1478 * through it's (group, element) and modifies it's content with
1480 * @param content new value to substitute with
1481 * @param group group of the ElVal to modify
1482 * @param element element of the ElVal to modify
1484 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1487 //TODO : homogeneiser les noms : SetPubElValByNumber qui appelle PubElValSet.SetElValueByNumber
1488 // pourquoi pas SetPubElValueByNumber ??
1491 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1495 * \ingroup gdcmHeader
1496 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1497 * through tag name and modifies it's content with the given value.
1498 * @param content new value to substitute with
1499 * @param TagName name of the tag to be modified
1501 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1502 return ( PubElValSet.SetElValueByName (content, TagName) );
1506 * \ingroup gdcmHeader
1507 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1508 * through it's (group, element) and modifies it's length with
1510 * \warning Use with extreme caution.
1511 * @param length new length to substitute with
1512 * @param group group of the ElVal to modify
1513 * @param element element of the ElVal to modify
1514 * @return 1 on success, 0 otherwise.
1517 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1519 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1523 * \ingroup gdcmHeader
1524 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1525 * through it's (group, element) and modifies it's content with
1527 * @param content new value to substitute with
1528 * @param group group of the ElVal to modify
1529 * @param element element of the ElVal to modify
1530 * @return 1 on success, 0 otherwise.
1532 int gdcmHeader::SetShaElValByNumber(string content,
1533 guint16 group, guint16 element) {
1534 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1538 * \ingroup gdcmHeader
1539 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1540 * through tag name and modifies it's content with the given value.
1541 * @param content new value to substitute with
1542 * @param ShadowTagName name of the tag to be modified
1544 int gdcmHeader::SetShaElValByName(string content, string ShadowTagName) {
1545 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1549 * \ingroup gdcmHeader
1550 * \brief Parses the header of the file but WITHOUT loading element values.
1552 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1553 gdcmElValue * newElValue = (gdcmElValue *)0;
1557 while ( (newElValue = ReadNextElement()) ) {
1558 SkipElementValue(newElValue);
1559 PubElValSet.Add(newElValue);
1566 // des que les element values sont chargees, stocker,
1567 // en une seule fois, dans des entiers
1568 // NX, NY, NZ, Bits allocated, Bits Stored, High Bit, Samples Per Pixel
1569 // (TODO : preciser les autres)
1570 // et refaire ceux des accesseurs qui renvoient les entiers correspondants
1572 // --> peut etre dangereux ?
1573 // si l'utilisateur modifie 'manuellement' l'un des paramètres
1574 // l'entier de sera pas modifié ...
1575 // (pb de la mise à jour en cas de redondance :-(
1578 * \ingroup gdcmHeader
1579 * \brief Retrieve the number of columns of image.
1580 * @return The encountered size when found, 0 by default.
1582 int gdcmHeader::GetXSize(void) {
1583 // We cannot check for "Columns" because the "Columns" tag is present
1584 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1585 string StrSize = GetPubElValByNumber(0x0028,0x0011);
1586 if (StrSize == "gdcm::Unfound")
1588 return atoi(StrSize.c_str());
1592 * \ingroup gdcmHeader
1593 * \brief Retrieve the number of lines of image.
1594 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1595 * @return The encountered size when found, 1 by default.
1597 int gdcmHeader::GetYSize(void) {
1598 // We cannot check for "Rows" because the "Rows" tag is present
1599 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1600 string StrSize = GetPubElValByNumber(0x0028,0x0010);
1601 if (StrSize != "gdcm::Unfound")
1602 return atoi(StrSize.c_str());
1606 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1607 // hence be a signal (1d image). So we default to 1:
1612 * \ingroup gdcmHeader
1613 * \brief Retrieve the number of planes of volume or the number
1614 * of frames of a multiframe.
1615 * \warning When present we consider the "Number of Frames" as the third
1616 * dimension. When absent we consider the third dimension as
1617 * being the "Planes" tag content.
1618 * @return The encountered size when found, 1 by default.
1620 int gdcmHeader::GetZSize(void) {
1621 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1622 // as the third dimension.
1623 string StrSize = GetPubElValByNumber(0x0028,0x0008);
1624 if (StrSize != "gdcm::Unfound")
1625 return atoi(StrSize.c_str());
1627 // We then consider the "Planes" entry as the third dimension [we
1628 // cannot retrieve by name since "Planes tag is present both in
1629 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1630 StrSize = GetPubElValByNumber(0x0028,0x0012);
1631 if (StrSize != "gdcm::Unfound")
1632 return atoi(StrSize.c_str());
1637 * \ingroup gdcmHeader
1638 * \brief Retrieve the number of Bits Stored
1639 * (as opposite to number of Bits Allocated)
1641 * @return The encountered number of Bits Stored, 0 by default.
1643 int gdcmHeader::GetBitsStored(void) {
1644 string StrSize = GetPubElValByNumber(0x0028,0x0101);
1645 if (StrSize == "gdcm::Unfound")
1647 return atoi(StrSize.c_str());
1651 * \ingroup gdcmHeader
1652 * \brief Retrieve the number of Samples Per Pixel
1653 * (1 : gray level, 3 : RGB)
1655 * @return The encountered number of Samples Per Pixel, 1 by default.
1657 int gdcmHeader::GetSamplesPerPixel(void) {
1658 string StrSize = GetPubElValByNumber(0x0028,0x0002);
1659 if (StrSize == "gdcm::Unfound")
1660 return 1; // Well, it's supposed to be mandatory ...
1661 return atoi(StrSize.c_str());
1665 * \ingroup gdcmHeader
1666 * \brief Return the size (in bytes) of a single pixel of data.
1667 * @return The size in bytes of a single pixel of data.
1670 int gdcmHeader::GetPixelSize(void) {
1671 string PixelType = GetPixelType();
1672 if (PixelType == "8U" || PixelType == "8S")
1674 if (PixelType == "16U" || PixelType == "16S")
1676 if (PixelType == "32U" || PixelType == "32S")
1678 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1683 * \ingroup gdcmHeader
1684 * \brief Build the Pixel Type of the image.
1685 * Possible values are:
1686 * - 8U unsigned 8 bit,
1687 * - 8S signed 8 bit,
1688 * - 16U unsigned 16 bit,
1689 * - 16S signed 16 bit,
1690 * - 32U unsigned 32 bit,
1691 * - 32S signed 32 bit,
1692 * \warning 12 bit images appear as 16 bit.
1695 string gdcmHeader::GetPixelType(void) {
1697 BitsAlloc = GetElValByName("Bits Allocated");
1698 if (BitsAlloc == "gdcm::Unfound") {
1699 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1700 BitsAlloc = string("16");
1702 if (BitsAlloc == "12")
1703 BitsAlloc = string("16");
1706 Signed = GetElValByName("Pixel Representation");
1707 if (Signed == "gdcm::Unfound") {
1708 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1709 BitsAlloc = string("0");
1712 Signed = string("U");
1714 Signed = string("S");
1716 return( BitsAlloc + Signed);
1721 * \ingroup gdcmHeader
1722 * \brief This predicate, based on hopefully reasonnable heuristics,
1723 * decides whether or not the current gdcmHeader was properly parsed
1724 * and contains the mandatory information for being considered as
1725 * a well formed and usable image.
1726 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1729 bool gdcmHeader::IsReadable(void) {
1730 if ( GetElValByName("Image Dimensions") != "gdcm::Unfound"
1731 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1734 if ( GetElValByName("Bits Allocated") == "gdcm::Unfound" )
1736 if ( GetElValByName("Bits Stored") == "gdcm::Unfound" )
1738 if ( GetElValByName("High Bit") == "gdcm::Unfound" )
1740 if ( GetElValByName("Pixel Representation") == "gdcm::Unfound" )
1746 * \ingroup gdcmHeader
1747 * \brief Small utility function that creates a new manually crafted
1748 * (as opposed as read from the file) gdcmElValue with user
1749 * specified name and adds it to the public tag hash table.
1750 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1751 * @param NewTagName The name to be given to this new tag.
1752 * @param VR The Value Representation to be given to this new tag.
1753 * @ return The newly hand crafted Element Value.
1755 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1756 gdcmElValue* NewElVal = (gdcmElValue*)0;
1757 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1758 guint32 FreeElem = 0;
1759 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1761 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1762 if (FreeElem == UINT32_MAX) {
1763 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1764 "Group 0xffff in Public Dict is full");
1765 return (gdcmElValue*)0;
1767 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1768 VR, "GDCM", NewTagName);
1769 NewElVal = new gdcmElValue(NewEntry);
1770 PubElValSet.Add(NewElVal);
1775 * \ingroup gdcmHeader
1776 * \brief Loads the element values of all the elements present in the
1777 * public tag based hash table.
1779 void gdcmHeader::LoadElements(void) {
1781 TagElValueHT ht = PubElValSet.GetTagHt();
1782 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1783 LoadElementValue(tag->second);
1788 * \ingroup gdcmHeader
1792 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1793 PubElValSet.Print(os);
1797 * \ingroup gdcmHeader
1801 void gdcmHeader::PrintPubDict(std::ostream & os) {
1802 RefPubDict->Print(os);
1806 * \ingroup gdcmHeader
1810 int gdcmHeader::Write(FILE * fp, FileType type) {
1811 return PubElValSet.Write(fp, type);
1815 * \ingroup gdcmHeader
1816 * \brief gets the info from 0028,0030 : Pixel Spacing
1818 * @return X dimension of a pixel
1820 float gdcmHeader::GetXSpacing(void) {
1821 float xspacing, yspacing;
1822 string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1824 if (StrSpacing == "gdcm::Unfound") {
1825 dbg.Verbose(0, "gdcmHeader::GetXSpacing: unfound Pixel Spacing (0028,0030)");
1828 if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1835 * \ingroup gdcmHeader
1836 * \brief gets the info from 0028,0030 : Pixel Spacing
1838 * @return Y dimension of a pixel
1840 float gdcmHeader::GetYSpacing(void) {
1841 float xspacing, yspacing;
1842 string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1844 if (StrSpacing == "gdcm::Unfound") {
1845 dbg.Verbose(0, "gdcmHeader::GetYSpacing: unfound Pixel Spacing (0028,0030)");
1848 if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1850 if (yspacing == 0.) {
1851 dbg.Verbose(0, "gdcmHeader::GetYSpacing: gdcmData/CT-MONO2-8-abdo.dcm problem");
1852 // seems to be a bug in the header ...
1853 sscanf( StrSpacing.c_str(), "%f\\0\\%f", &xspacing, &yspacing);
1860 *\ingroup gdcmHeader
1861 *\brief gets the info from 0018,0088 : Space Between Slices
1862 *\ else from 0018,0050 : Slice Thickness
1864 * @return Z dimension of a voxel-to be
1866 float gdcmHeader::GetZSpacing(void) {
1867 // TODO : translate into English
1868 // Spacing Between Slices : distance entre le milieu de chaque coupe
1869 // Les coupes peuvent etre :
1870 // jointives (Spacing between Slices = Slice Thickness)
1871 // chevauchantes (Spacing between Slices < Slice Thickness)
1872 // disjointes (Spacing between Slices > Slice Thickness)
1873 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
1874 // ca interesse le physicien de l'IRM, pas le visualisateur de volumes ...
1875 // Si le Spacing Between Slices est absent,
1876 // on suppose que les coupes sont jointives
1878 string StrSpacingBSlices = GetPubElValByNumber(0x0018,0x0088);
1880 if (StrSpacingBSlices == "gdcm::Unfound") {
1881 dbg.Verbose(0, "gdcmHeader::GetZSpacing: unfound StrSpacingBSlices");
1882 string StrSliceThickness = GetPubElValByNumber(0x0018,0x0050);
1883 if (StrSliceThickness == "gdcm::Unfound")
1886 // if no 'Spacing Between Slices' is found,
1887 // we assume slices join together
1888 // (no overlapping, no interslice gap)
1889 // if they don't, we're fucked up
1890 return atof(StrSliceThickness.c_str());
1892 return atof(StrSpacingBSlices.c_str());
1897 // Image Position Patient (0020,0032):
1898 // If not found (ACR_NEMA) we try Image Position (0020,0030)
1899 // If not found (ACR-NEMA), we consider Slice Location (0020,1041)
1900 // or Location (0020,0050)
1901 // as the Z coordinate,
1902 // 0. for all the coordinates if nothing is found
1903 // TODO : find a way to inform the caller nothing was found
1904 // TODO : How to tell the caller a wrong number of values was found?
1908 * \ingroup gdcmHeader
1909 * \brief gets the info from 0020,0032 : Image Position Patient
1910 *\ else from 0020,0030 : Image Position (RET)
1912 * @return up-left image corner position
1914 float gdcmHeader::GetXImagePosition(void) {
1915 float xImPos, yImPos, zImPos;
1916 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1918 if (StrImPos == "gdcm::Unfound") {
1919 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Image Position Patient (0020,0032)");
1920 StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1921 if (StrImPos == "gdcm::Unfound") {
1922 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Image Position (RET) (0020,0030)");
1923 // How to tell the caller nothing was found ?
1927 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1933 * \ingroup gdcmHeader
1934 * \brief gets the info from 0020,0032 : Image Position Patient
1935 * \ else from 0020,0030 : Image Position (RET)
1937 * @return up-left image corner position
1939 float gdcmHeader::GetYImagePosition(void) {
1940 float xImPos, yImPos, zImPos;
1941 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1943 if (StrImPos == "gdcm::Unfound") {
1944 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position Patient (0020,0032)");
1945 StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1946 if (StrImPos == "gdcm::Unfound") {
1947 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position (RET) (0020,0030)");
1951 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1957 * \ingroup gdcmHeader
1958 * \brief gets the info from 0020,0032 : Image Position Patient
1959 * \ else from 0020,0030 : Image Position (RET)
1960 * \ else from 0020,1041 : Slice Location
1961 * \ else from 0020,0050 : Location
1963 * @return up-left image corner position
1965 float gdcmHeader::GetZImagePosition(void) {
1966 float xImPos, yImPos, zImPos;
1967 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1968 if (StrImPos != "gdcm::Unfound") {
1969 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3) {
1970 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Image Position Patient (0020,0032)");
1971 return 0.; // bug in the element 0x0020,0x0032
1976 StrImPos = GetPubElValByNumber(0x0020,0x0030); // For ACR-NEMA images
1977 if (StrImPos != "gdcm::Unfound") {
1978 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3) {
1979 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Image Position (RET) (0020,0030)");
1980 return 0.; // bug in the element 0x0020,0x0032
1985 string StrSliceLocation = GetPubElValByNumber(0x0020,0x1041);// for *very* old ACR-NEMA images
1986 if (StrSliceLocation != "gdcm::Unfound") {
1987 if( sscanf( StrSliceLocation.c_str(), "%f", &zImPos) !=1) {
1988 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Slice Location (0020,1041)");
1989 return 0.; // bug in the element 0x0020,0x1041
1994 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: unfound Slice Location (0020,1041)");
1995 string StrLocation = GetPubElValByNumber(0x0020,0x0050);
1996 if (StrLocation != "gdcm::Unfound") {
1997 if( sscanf( StrLocation.c_str(), "%f", &zImPos) !=1) {
1998 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Location (0020,0050)");
1999 return 0.; // bug in the element 0x0020,0x0050
2004 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Location (0020,0050)");
2005 return 0.; // Hopeless