1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.70 2003/06/20 14:17:47 jpr Exp $
9 #include <netinet/in.h>
11 #include <cctype> // for isalpha
14 #include "gdcmHeader.h"
18 // TODO : remove DEBUG
21 // Refer to gdcmHeader::CheckSwap()
22 #define HEADER_LENGTH_TO_READ 256
23 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
24 #define _MaxSizeLoadElementValue_ 1024
32 void gdcmHeader::Initialise(void) {
33 dicom_vr = gdcmGlobal::GetVR();
34 dicom_ts = gdcmGlobal::GetTS();
35 Dicts = gdcmGlobal::GetDicts();
36 RefPubDict = Dicts->GetDefaultPubDict();
37 RefShaDict = (gdcmDict*)0;
46 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) {
47 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
48 filename = InFilename;
50 if ( !OpenFile(exception_on_error))
63 gdcmHeader::gdcmHeader(bool exception_on_error) {
64 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
74 bool gdcmHeader::OpenFile(bool exception_on_error)
75 throw(gdcmFileError) {
76 fp=fopen(filename.c_str(),"rb");
77 if(exception_on_error) {
79 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
83 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
93 bool gdcmHeader::CloseFile(void) {
94 int closed = fclose(fp);
102 * \ingroup gdcmHeader
107 gdcmHeader::~gdcmHeader (void) {
108 dicom_vr = (gdcmVR*)0;
109 Dicts = (gdcmDictSet*)0;
110 RefPubDict = (gdcmDict*)0;
111 RefShaDict = (gdcmDict*)0;
117 // META Meta Information
129 // NMI Nuclear Medicine
131 // BFS Basic Film Session
132 // BFB Basic Film Box
133 // BIB Basic Image Box
148 * \ingroup gdcmHeader
149 * \brief Discover what the swap code is (among little endian, big endian,
150 * bad little endian, bad big endian).
153 void gdcmHeader::CheckSwap()
155 // The only guaranted way of finding the swap code is to find a
156 // group tag since we know it's length has to be of four bytes i.e.
157 // 0x00000004. Finding the swap code in then straigthforward. Trouble
158 // occurs when we can't find such group...
160 guint32 x=4; // x : pour ntohs
161 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
165 char deb[HEADER_LENGTH_TO_READ];
167 // First, compare HostByteOrder and NetworkByteOrder in order to
168 // determine if we shall need to swap bytes (i.e. the Endian type).
174 // The easiest case is the one of a DICOM header, since it possesses a
175 // file preamble where it suffice to look for the string "DICM".
176 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
179 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
180 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
181 // Next, determine the value representation (VR). Let's skip to the
182 // first element (0002, 0000) and check there if we find "UL"
183 // - or "OB" if the 1st one is (0002,0001) -,
184 // in which case we (almost) know it is explicit VR.
185 // WARNING: if it happens to be implicit VR then what we will read
186 // is the length of the group. If this ascii representation of this
187 // length happens to be "UL" then we shall believe it is explicit VR.
188 // FIXME: in order to fix the above warning, we could read the next
189 // element value (or a couple of elements values) in order to make
190 // sure we are not commiting a big mistake.
192 // * the 128 bytes of File Preamble (often padded with zeroes),
193 // * the 4 bytes of "DICM" string,
194 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
195 // i.e. a total of 136 bytes.
198 // Use gdcmHeader::dicom_vr to test all the possibilities
199 // instead of just checking for UL, OB and UI !?
200 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
201 (memcmp(entCur, "OB", (size_t)2) == 0) ||
202 (memcmp(entCur, "UI", (size_t)2) == 0) )
204 filetype = ExplicitVR;
205 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
206 "explicit Value Representation");
208 filetype = ImplicitVR;
209 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
210 "not an explicit Value Representation");
215 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
216 "HostByteOrder != NetworkByteOrder");
219 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
220 "HostByteOrder = NetworkByteOrder");
223 // Position the file position indicator at first tag (i.e.
224 // after the file preamble and the "DICM" string).
226 fseek (fp, 132L, SEEK_SET);
230 // Alas, this is not a DicomV3 file and whatever happens there is no file
231 // preamble. We can reset the file position indicator to where the data
232 // is (i.e. the beginning of the file).
233 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
236 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
237 // By clean we mean that the length of the first tag is written down.
238 // If this is the case and since the length of the first group HAS to be
239 // four (bytes), then determining the proper swap code is straightforward.
242 // We assume the array of char we are considering contains the binary
243 // representation of a 32 bits integer. Hence the following dirty
245 s = *((guint32 *)(entCur));
265 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
266 "ACR/NEMA unfound swap info (time to raise bets)");
269 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
270 // It is time for despaired wild guesses. So, let's assume this file
271 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
272 // not present. Then the only info we have is the net2host one.
282 * \ingroup gdcmHeader
287 void gdcmHeader::SwitchSwapToBigEndian(void) {
288 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
289 "Switching to BigEndian mode.");
307 * \ingroup gdcmHeader
308 * \brief Find the value representation of the current tag.
310 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
311 if (filetype != ExplicitVR)
317 char msg[100]; // for sprintf. Sorry
319 long PositionOnEntry = ftell(fp);
320 // Warning: we believe this is explicit VR (Value Representation) because
321 // we used a heuristic that found "UL" in the first tag. Alas this
322 // doesn't guarantee that all the tags will be in explicit VR. In some
323 // cases (see e-film filtered files) one finds implicit VR tags mixed
324 // within an explicit VR file. Hence we make sure the present tag
325 // is in explicit VR and try to fix things if it happens not to be
327 bool RealExplicit = true;
329 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
333 // Assume we are reading a falsely explicit VR file i.e. we reached
334 // a tag where we expect reading a VR but are in fact we read the
335 // first to bytes of the length. Then we will interogate (through find)
336 // the dicom_vr dictionary with oddities like "\004\0" which crashes
337 // both GCC and VC++ implementations of the STL map. Hence when the
338 // expected VR read happens to be non-ascii characters we consider
339 // we hit falsely explicit VR tag.
341 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
342 RealExplicit = false;
344 // CLEANME searching the dicom_vr at each occurence is expensive.
345 // PostPone this test in an optional integrity check at the end
346 // of parsing or only in debug mode.
347 if ( RealExplicit && !dicom_vr->Count(vr) )
350 if ( RealExplicit ) {
351 if ( ElVal->IsVrUnknown() ) {
352 // When not a dictionary entry, we can safely overwrite the vr.
356 if ( ElVal->GetVR() == vr ) {
357 // The vr we just read and the dictionary agree. Nothing to do.
360 // The vr present in the file and the dictionary disagree. We assume
361 // the file writer knew best and use the vr of the file. Since it would
362 // be unwise to overwrite the vr of a dictionary (since it would
363 // compromise it's next user), we need to clone the actual DictEntry
364 // and change the vr for the read one.
365 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
370 ElVal->SetDictEntry(NewTag);
374 // We thought this was explicit VR, but we end up with an
375 // implicit VR tag. Let's backtrack.
377 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", ElVal->GetGroup(),ElVal->GetElement());
378 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
380 fseek(fp, PositionOnEntry, SEEK_SET);
381 // When this element is known in the dictionary we shall use, e.g. for
382 // the semantics (see the usage of IsAnInteger), the vr proposed by the
383 // dictionary entry. Still we have to flag the element as implicit since
384 // we know now our assumption on expliciteness is not furfilled.
386 if ( ElVal->IsVrUnknown() )
387 ElVal->SetVR("Implicit");
388 ElVal->SetImplicitVr();
392 * \ingroup gdcmHeader
393 * \brief Determines if the Transfer Syntax was allready encountered
394 * and if it corresponds to a ImplicitVRLittleEndian one.
396 * @return True when ImplicitVRLittleEndian found. False in all other cases.
398 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
399 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
402 LoadElementValueSafe(Element);
403 string Transfer = Element->GetValue();
404 if ( Transfer == "1.2.840.10008.1.2" )
410 * \ingroup gdcmHeader
411 * \brief Determines if the Transfer Syntax was allready encountered
412 * and if it corresponds to a ExplicitVRLittleEndian one.
414 * @return True when ExplicitVRLittleEndian found. False in all other cases.
416 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
417 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
420 LoadElementValueSafe(Element);
421 string Transfer = Element->GetValue();
422 if ( Transfer == "1.2.840.10008.1.2.1" )
428 * \ingroup gdcmHeader
429 * \brief Determines if the Transfer Syntax was allready encountered
430 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
432 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
434 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
435 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
438 LoadElementValueSafe(Element);
439 string Transfer = Element->GetValue();
440 if ( Transfer == "1.2.840.10008.1.2.1.99" )
446 * \ingroup gdcmHeader
447 * \brief Determines if the Transfer Syntax was allready encountered
448 * and if it corresponds to a Explicit VR Big Endian one.
450 * @return True when big endian found. False in all other cases.
452 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
453 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
456 LoadElementValueSafe(Element);
457 string Transfer = Element->GetValue();
458 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
464 * \ingroup gdcmHeader
465 * \brief Determines if the Transfer Syntax was allready encountered
466 * and if it corresponds to a JPEGBaseLineProcess1 one.
468 * @return True when JPEGBaseLineProcess1found. False in all other cases.
470 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
471 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
474 LoadElementValueSafe(Element);
475 string Transfer = Element->GetValue();
476 if ( Transfer == "1.2.840.10008.1.2.4.50" )
482 * \ingroup gdcmHeader
487 bool gdcmHeader::IsJPEGLossless(void) {
488 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
489 // faire qq chose d'intelligent a la place de ça
492 LoadElementValueSafe(Element);
493 const char * Transfert = Element->GetValue().c_str();
494 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
495 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
501 * \ingroup gdcmHeader
502 * \brief Determines if the Transfer Syntax was allready encountered
503 * and if it corresponds to a JPEGExtendedProcess2-4 one.
505 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
507 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
508 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
511 LoadElementValueSafe(Element);
512 string Transfer = Element->GetValue();
513 if ( Transfer == "1.2.840.10008.1.2.4.51" )
519 * \ingroup gdcmHeader
520 * \brief Determines if the Transfer Syntax was allready encountered
521 * and if it corresponds to a JPEGExtendeProcess3-5 one.
523 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
525 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
526 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
529 LoadElementValueSafe(Element);
530 string Transfer = Element->GetValue();
531 if ( Transfer == "1.2.840.10008.1.2.4.52" )
537 * \ingroup gdcmHeader
538 * \brief Determines if the Transfer Syntax was allready encountered
539 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
541 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
544 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
545 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
548 LoadElementValueSafe(Element);
549 string Transfer = Element->GetValue();
550 if ( Transfer == "1.2.840.10008.1.2.4.53" )
556 * \ingroup gdcmHeader
557 * \brief Predicate for dicom version 3 file.
558 * @return True when the file is a dicom version 3.
560 bool gdcmHeader::IsDicomV3(void) {
561 if ( (filetype == ExplicitVR)
562 || (filetype == ImplicitVR) )
568 * \ingroup gdcmHeader
569 * \brief When the length of an element value is obviously wrong (because
570 * the parser went Jabberwocky) one can hope improving things by
571 * applying this heuristic.
573 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
574 if ( FoundLength == 0xffffffff)
576 ElVal->SetLength(FoundLength);
580 * \ingroup gdcmHeader
585 guint32 gdcmHeader::FindLengthOB(void) {
586 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
589 long PositionOnEntry = ftell(fp);
590 bool FoundSequenceDelimiter = false;
591 guint32 TotalLength = 0;
594 while ( ! FoundSequenceDelimiter) {
598 if (DEBUG) printf ("dans FindLengthOB (%04x,%04x)\n",g,n);
600 if (DEBUG) printf("en %d o(%o) x(%x)\n",l,l,l);
604 TotalLength += 4; // We even have to decount the group and element
606 if ( g != 0xfffe && g!=0xb00c ) /*for bogus headerJPR */ {
607 char msg[100]; // for sprintf. Sorry
608 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
609 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
611 if (DEBUG) printf("en %d o(%o) x(%x)\n",l,l,l);
616 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header JPR */
617 FoundSequenceDelimiter = true;
618 else if ( n != 0xe000 ){
619 char msg[100]; // for sprintf. Sorry
620 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
621 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
622 if (DEBUG) printf("wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
626 ItemLength = ReadInt32();
627 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
628 // the ItemLength with ReadInt32
630 if (DEBUG) printf("TotalLength %d\n",TotalLength);
631 SkipBytes(ItemLength);
633 fseek(fp, PositionOnEntry, SEEK_SET);
638 * \ingroup gdcmHeader
643 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
644 guint16 element = ElVal->GetElement();
645 guint16 group = ElVal->GetGroup(); // JPR a virer
646 string vr = ElVal->GetVR();
648 if( (element == 0x0010) && (group == 0x7fe0) ) {// JPR
651 dbg.Verbose(2, "gdcmHeader::FindLength: ", // JPR
652 "on est sur 7fe0 0010");
655 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
656 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
658 // The following reserved two bytes (see PS 3.5-2001, section
659 // 7.1.2 Data element structure with explicit vr p27) must be
660 // skipped before proceeding on reading the length on 4 bytes.
661 fseek(fp, 2L, SEEK_CUR);
663 guint32 length32 = ReadInt32();
664 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
665 ElVal->SetLength(FindLengthOB());
668 FixFoundLength(ElVal, length32);
672 // Length is encoded on 2 bytes.
673 length16 = ReadInt16();
675 // We can tell the current file is encoded in big endian (like
676 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
677 // and it's value is the one of the encoding of a big endian file.
678 // In order to deal with such big endian encoded files, we have
679 // (at least) two strategies:
680 // * when we load the "Transfer Syntax" tag with value of big endian
681 // encoding, we raise the proper flags. Then we wait for the end
682 // of the META group (0x0002) among which is "Transfer Syntax",
683 // before switching the swap code to big endian. We have to postpone
684 // the switching of the swap code since the META group is fully encoded
685 // in little endian, and big endian coding only starts at the next
686 // group. The corresponding code can be hard to analyse and adds
687 // many additional unnecessary tests for regular tags.
688 // * the second strategy consists in waiting for trouble, that shall
689 // appear when we find the first group with big endian encoding. This
690 // is easy to detect since the length of a "Group Length" tag (the
691 // ones with zero as element number) has to be of 4 (0x0004). When we
692 // encouter 1024 (0x0400) chances are the encoding changed and we
693 // found a group with big endian encoding.
694 // We shall use this second strategy. In order to make sure that we
695 // can interpret the presence of an apparently big endian encoded
696 // length of a "Group Length" without committing a big mistake, we
697 // add an additional check: we look in the allready parsed elements
698 // for the presence of a "Transfer Syntax" whose value has to be "big
699 // endian encoding". When this is the case, chances are we have got our
700 // hands on a big endian encoded file: we switch the swap code to
701 // big endian and proceed...
702 if ( (element == 0x0000) && (length16 == 0x0400) ) {
703 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
704 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
709 SwitchSwapToBigEndian();
710 // Restore the unproperly loaded values i.e. the group, the element
711 // and the dictionary entry depending on them.
712 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
713 guint16 CorrectElem = SwapShort(ElVal->GetElement());
714 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
717 // This correct tag is not in the dictionary. Create a new one.
718 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
720 // FIXME this can create a memory leaks on the old entry that be
721 // left unreferenced.
722 ElVal->SetDictEntry(NewTag);
725 // Heuristic: well some files are really ill-formed.
726 if ( length16 == 0xffff) {
728 dbg.Verbose(0, "gdcmHeader::FindLength",
729 "Erroneous element length fixed.");
731 FixFoundLength(ElVal, (guint32)length16);
735 // Either implicit VR or a non DICOM conformal (see not below) explicit
736 // VR that ommited the VR of (at least) this element. Farts happen.
737 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
738 // on Data elements "Implicit and Explicit VR Data Elements shall
739 // not coexist in a Data Set and Data Sets nested within it".]
740 // Length is on 4 bytes.
741 FixFoundLength(ElVal, ReadInt32());
745 * \ingroup gdcmHeader
746 * \brief Swaps back the bytes of 4-byte long integer accordingly to
749 * @return The suggested integer.
751 guint32 gdcmHeader::SwapLong(guint32 a) {
756 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
757 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
761 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
765 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
768 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
775 * \ingroup gdcmHeader
776 * \brief Swaps the bytes so they agree with the processor order
777 * @return The properly swaped 16 bits integer.
779 guint16 gdcmHeader::SwapShort(guint16 a) {
780 if ( (sw==4321) || (sw==2143) )
781 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
786 * \ingroup gdcmHeader
791 void gdcmHeader::SkipBytes(guint32 NBytes) {
792 //FIXME don't dump the returned value
793 (void)fseek(fp, (long)NBytes, SEEK_CUR);
797 * \ingroup gdcmHeader
802 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
803 SkipBytes(ElVal->GetLength());
807 * \ingroup gdcmHeader
812 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
815 if ((guint32)NewSize >= (guint32)0xffffffff) {
816 MaxSizeLoadElementValue = 0xffffffff;
819 MaxSizeLoadElementValue = NewSize;
823 * \ingroup gdcmHeader
824 * \brief Loads the element content if it's length is not bigger
825 * than the value specified with
826 * gdcmHeader::SetMaxSizeLoadElementValue()
828 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
830 guint16 group = ElVal->GetGroup();
831 string vr = ElVal->GetVR();
832 guint32 length = ElVal->GetLength();
833 bool SkipLoad = false;
835 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
837 // FIXME Sequences not treated yet !
839 // Ne faudrait-il pas au contraire trouver immediatement
840 // une maniere 'propre' de traiter les sequences (vr = SQ)
841 // car commencer par les ignorer risque de conduire a qq chose
842 // qui pourrait ne pas etre generalisable
843 // Well, I'm expecting your code !!!
848 // Heuristic : a sequence "contains" a set of tags (called items). It looks
849 // like the last tag of a sequence (the one that terminates the sequence)
850 // has a group of 0xfffe (with a dummy length).
851 if( group == 0xfffe )
856 ElVal->SetValue("gdcm::Skipped");
860 // When the length is zero things are easy:
866 // The elements whose length is bigger than the specified upper bound
867 // are not loaded. Instead we leave a short notice of the offset of
868 // the element content and it's length.
869 if (length > MaxSizeLoadElementValue) {
871 s << "gdcm::NotLoaded.";
872 s << " Address:" << (long)ElVal->GetOffset();
873 s << " Length:" << ElVal->GetLength();
874 ElVal->SetValue(s.str());
878 // When an integer is expected, read and convert the following two or
879 // four bytes properly i.e. as an integer as opposed to a string.
881 // pour les elements de Value Multiplicity > 1
882 // on aura en fait une serie d'entiers
884 // on devrait pouvoir faire + compact (?)
886 if ( IsAnInteger(ElVal) ) {
890 if (vr == "US" || vr == "SS") {
892 NewInt = ReadInt16();
895 for (int i=1; i < nbInt; i++) {
897 NewInt = ReadInt16();
902 } else if (vr == "UL" || vr == "SL") {
904 NewInt = ReadInt32();
907 for (int i=1; i < nbInt; i++) {
909 NewInt = ReadInt32();
914 ElVal->SetValue(s.str());
918 // We need an additional byte for storing \0 that is not on disk
919 char* NewValue = (char*)malloc(length+1);
921 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
926 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
927 if ( item_read != 1 ) {
929 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
930 ElVal->SetValue("gdcm::UnRead");
933 ElVal->SetValue(NewValue);
938 * \ingroup gdcmHeader
939 * \brief Loads the element while preserving the current
940 * underlying file position indicator as opposed to
941 * to LoadElementValue that modifies it.
942 * @param ElVal Element whose value shall be loaded.
945 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
946 long PositionOnEntry = ftell(fp);
947 LoadElementValue(ElVal);
948 fseek(fp, PositionOnEntry, SEEK_SET);
952 * \ingroup gdcmHeader
957 guint16 gdcmHeader::ReadInt16(void) {
960 item_read = fread (&g, (size_t)2,(size_t)1, fp);
961 if ( item_read != 1 ) {
962 dbg.Verbose(1, "gdcmHeader::ReadInt16", " Failed to read :");
964 dbg.Verbose(1, "gdcmHeader::ReadInt16", " End of File encountered");
966 dbg.Verbose(1, "gdcmHeader::ReadInt16", " File Error");
976 * \ingroup gdcmHeader
981 guint32 gdcmHeader::ReadInt32(void) {
984 item_read = fread (&g, (size_t)4,(size_t)1, fp);
985 if ( item_read != 1 ) {
987 dbg.Verbose(1, "gdcmHeader::ReadInt32", " Failed to read :");
989 dbg.Verbose(1, "gdcmHeader::ReadInt32", " End of File encountered");
991 dbg.Verbose(1, "gdcmHeader::ReadInt32", " File Error");
1001 * \ingroup gdcmHeader
1006 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1008 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1010 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1011 "failed to Locate gdcmElValue");
1012 return (gdcmElValue*)0;
1018 * \ingroup gdcmHeader
1019 * \brief Build a new Element Value from all the low level arguments.
1020 * Check for existence of dictionary entry, and build
1021 * a default one when absent.
1022 * @param Group group of the underlying DictEntry
1023 * @param Elem element of the underlying DictEntry
1025 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1026 // Find out if the tag we encountered is in the dictionaries:
1027 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1029 NewTag = new gdcmDictEntry(Group, Elem);
1031 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1033 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1034 "failed to allocate gdcmElValue");
1035 return (gdcmElValue*)0;
1041 * \ingroup gdcmHeader
1045 int gdcmHeader::ReplaceOrCreateByNumber(string Value, guint16 Group, guint16 Elem ) {
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);
1068 * \ingroup gdcmHeader
1069 * \brief Build a new Element Value from all the low level arguments.
1070 * Check for existence of dictionary entry, and build
1071 * a default one when absent.
1072 * @param Name Name of the underlying DictEntry
1074 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
1076 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1078 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1080 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1082 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1083 "failed to allocate gdcmElValue");
1084 return (gdcmElValue*)0;
1090 * \ingroup gdcmHeader
1091 * \brief Read the next tag but WITHOUT loading it's value
1092 * @return On succes the newly created ElValue, NULL on failure.
1094 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1097 gdcmElValue * NewElVal;
1102 if ( (g==0x7fe0) && (n==0x0010) )
1104 printf("in gdcmHeader::ReadNextElement try to read 7fe0 0010 \n");
1107 // We reached the EOF (or an error occured) and header parsing
1108 // has to be considered as finished.
1109 return (gdcmElValue *)0;
1111 NewElVal = NewElValueByNumber(g, n);
1113 FindLength(NewElVal);
1116 if (DEBUG) printf("in gdcmHeader::ReadNextElement : g %04x n %04x errno %d\n",g, n, errno);
1117 return (gdcmElValue *)0;
1119 NewElVal->SetOffset(ftell(fp));
1120 if ( (g==0x7fe0) && (n==0x0010) )
1122 printf("sortie de gdcmHeader::ReadNextElement 7fe0 0010 \n");
1127 * \ingroup gdcmHeader
1128 * \brief Apply some heuristics to predict wether the considered
1129 * element value contains/represents an integer or not.
1130 * @param ElVal The element value on which to apply the predicate.
1131 * @return The result of the heuristical predicate.
1133 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1134 guint16 group = ElVal->GetGroup();
1135 guint16 element = ElVal->GetElement();
1136 string vr = ElVal->GetVR();
1137 guint32 length = ElVal->GetLength();
1139 // When we have some semantics on the element we just read, and if we
1140 // a priori know we are dealing with an integer, then we shall be
1141 // able to swap it's element value properly.
1142 if ( element == 0 ) { // This is the group length of the group
1146 if (DEBUG) printf("Erroneous Group Length element length (%04x , %04x) : %d\n",
1147 group, element,length);
1149 dbg.Error("gdcmHeader::IsAnInteger",
1150 "Erroneous Group Length element length.");
1153 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1160 * \ingroup gdcmHeader
1161 * \brief Recover the offset (from the beginning of the file) of the pixels.
1163 size_t gdcmHeader::GetPixelOffset(void) {
1164 // If this file complies with the norm we should encounter the
1165 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1166 // the group that contains the pixel data (hence the "Pixel Data"
1167 // is found by indirection through the "Image Location").
1168 // Inside the group pointed by "Image Location" the searched element
1169 // is conventionally the element 0x0010 (when the norm is respected).
1170 // When the "Image Location" is absent we default to group 0x7fe0.
1173 string ImageLocation = GetPubElValByName("Image Location");
1174 if ( ImageLocation == "gdcm::Unfound" ) {
1177 grPixel = (guint16) atoi( ImageLocation.c_str() );
1179 if (grPixel != 0x7fe0)
1180 // This is a kludge for old dirty Philips imager.
1185 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1188 return PixelElement->GetOffset();
1194 * \ingroup gdcmHeader
1195 * \brief Searches both the public and the shadow dictionary (when they
1196 * exist) for the presence of the DictEntry with given
1197 * group and element. The public dictionary has precedence on the
1199 * @param group group of the searched DictEntry
1200 * @param element element of the searched DictEntry
1201 * @return Corresponding DictEntry when it exists, NULL otherwise.
1203 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1205 gdcmDictEntry * found = (gdcmDictEntry*)0;
1206 if (!RefPubDict && !RefShaDict) {
1207 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1208 "we SHOULD have a default dictionary");
1211 found = RefPubDict->GetTagByNumber(group, element);
1216 found = RefShaDict->GetTagByNumber(group, element);
1224 * \ingroup gdcmHeader
1225 * \brief Searches both the public and the shadow dictionary (when they
1226 * exist) for the presence of the DictEntry with given name.
1227 * The public dictionary has precedence on the shadow one.
1228 * @param Name name of the searched DictEntry
1229 * @return Corresponding DictEntry when it exists, NULL otherwise.
1231 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1232 gdcmDictEntry * found = (gdcmDictEntry*)0;
1233 if (!RefPubDict && !RefShaDict) {
1234 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1235 "we SHOULD have a default dictionary");
1238 found = RefPubDict->GetTagByName(Name);
1243 found = RefShaDict->GetTagByName(Name);
1251 * \ingroup gdcmHeader
1252 * \brief Searches within the public dictionary for element value of
1254 * @param group Group of the researched tag.
1255 * @param element Element of the researched tag.
1256 * @return Corresponding element value when it exists, and the string
1257 * "gdcm::Unfound" otherwise.
1259 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1260 return PubElValSet.GetElValueByNumber(group, element);
1264 * \ingroup gdcmHeader
1265 * \brief Searches within the public dictionary for element value
1266 * representation of a given tag.
1268 * Obtaining the VR (Value Representation) might be needed by caller
1269 * to convert the string typed content to caller's native type
1270 * (think of C++ vs Python). The VR is actually of a higher level
1271 * of semantics than just the native C++ type.
1272 * @param group Group of the researched tag.
1273 * @param element Element of the researched tag.
1274 * @return Corresponding element value representation when it exists,
1275 * and the string "gdcm::Unfound" otherwise.
1277 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1278 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1280 return "gdcm::Unfound";
1281 return elem->GetVR();
1285 * \ingroup gdcmHeader
1286 * \brief Searches within the public dictionary for element value of
1288 * @param TagName name of the researched element.
1289 * @return Corresponding element value when it exists, and the string
1290 * "gdcm::Unfound" otherwise.
1292 string gdcmHeader::GetPubElValByName(string TagName) {
1293 return PubElValSet.GetElValueByName(TagName);
1297 * \ingroup gdcmHeader
1298 * \brief Searches within the elements parsed with the public dictionary for
1299 * the element value representation of a given tag.
1301 * Obtaining the VR (Value Representation) might be needed by caller
1302 * to convert the string typed content to caller's native type
1303 * (think of C++ vs Python). The VR is actually of a higher level
1304 * of semantics than just the native C++ type.
1305 * @param TagName name of the researched element.
1306 * @return Corresponding element value representation when it exists,
1307 * and the string "gdcm::Unfound" otherwise.
1309 string gdcmHeader::GetPubElValRepByName(string TagName) {
1310 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1312 return "gdcm::Unfound";
1313 return elem->GetVR();
1317 * \ingroup gdcmHeader
1318 * \brief Searches within elements parsed with the SHADOW dictionary
1319 * for the element value of a given tag.
1320 * @param group Group of the researched tag.
1321 * @param element Element of the researched tag.
1322 * @return Corresponding element value representation when it exists,
1323 * and the string "gdcm::Unfound" otherwise.
1325 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1326 return ShaElValSet.GetElValueByNumber(group, element);
1330 * \ingroup gdcmHeader
1331 * \brief Searches within the elements parsed with the SHADOW dictionary
1332 * for the element value representation of a given tag.
1334 * Obtaining the VR (Value Representation) might be needed by caller
1335 * to convert the string typed content to caller's native type
1336 * (think of C++ vs Python). The VR is actually of a higher level
1337 * of semantics than just the native C++ type.
1338 * @param group Group of the researched tag.
1339 * @param element Element of the researched tag.
1340 * @return Corresponding element value representation when it exists,
1341 * and the string "gdcm::Unfound" otherwise.
1343 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1344 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1346 return "gdcm::Unfound";
1347 return elem->GetVR();
1351 * \ingroup gdcmHeader
1352 * \brief Searches within the elements parsed with the shadow dictionary
1353 * for an element value of given tag.
1354 * @param TagName name of the researched element.
1355 * @return Corresponding element value when it exists, and the string
1356 * "gdcm::Unfound" otherwise.
1358 string gdcmHeader::GetShaElValByName(string TagName) {
1359 return ShaElValSet.GetElValueByName(TagName);
1363 * \ingroup gdcmHeader
1364 * \brief Searches within the elements parsed with the shadow dictionary for
1365 * the element value representation of a given tag.
1367 * Obtaining the VR (Value Representation) might be needed by caller
1368 * to convert the string typed content to caller's native type
1369 * (think of C++ vs Python). The VR is actually of a higher level
1370 * of semantics than just the native C++ type.
1371 * @param TagName name of the researched element.
1372 * @return Corresponding element value representation when it exists,
1373 * and the string "gdcm::Unfound" otherwise.
1375 string gdcmHeader::GetShaElValRepByName(string TagName) {
1376 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1378 return "gdcm::Unfound";
1379 return elem->GetVR();
1383 * \ingroup gdcmHeader
1384 * \brief Searches within elements parsed with the public dictionary
1385 * and then within the elements parsed with the shadow dictionary
1386 * for the element value of a given tag.
1387 * @param group Group of the researched tag.
1388 * @param element Element of the researched tag.
1389 * @return Corresponding element value representation when it exists,
1390 * and the string "gdcm::Unfound" otherwise.
1392 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1393 string pub = GetPubElValByNumber(group, element);
1396 return GetShaElValByNumber(group, element);
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 representation of a given tag.
1405 * Obtaining the VR (Value Representation) might be needed by caller
1406 * to convert the string typed content to caller's native type
1407 * (think of C++ vs Python). The VR is actually of a higher level
1408 * of semantics than just the native C++ type.
1409 * @param group Group of the researched tag.
1410 * @param element Element of the researched tag.
1411 * @return Corresponding element value representation when it exists,
1412 * and the string "gdcm::Unfound" otherwise.
1414 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1415 string pub = GetPubElValRepByNumber(group, element);
1418 return GetShaElValRepByNumber(group, element);
1422 * \ingroup gdcmHeader
1423 * \brief Searches within elements parsed with the public dictionary
1424 * and then within the elements parsed with the shadow dictionary
1425 * for the element value of a given tag.
1426 * @param TagName name of the researched element.
1427 * @return Corresponding element value when it exists,
1428 * and the string "gdcm::Unfound" otherwise.
1430 string gdcmHeader::GetElValByName(string TagName) {
1431 string pub = GetPubElValByName(TagName);
1434 return GetShaElValByName(TagName);
1438 * \ingroup gdcmHeader
1439 * \brief Searches within elements parsed with the public dictionary
1440 * and then within the elements parsed with the shadow dictionary
1441 * for the element value representation of a given tag.
1443 * Obtaining the VR (Value Representation) might be needed by caller
1444 * to convert the string typed content to caller's native type
1445 * (think of C++ vs Python). The VR is actually of a higher level
1446 * of semantics than just the native C++ type.
1447 * @param TagName name of the researched element.
1448 * @return Corresponding element value representation when it exists,
1449 * and the string "gdcm::Unfound" otherwise.
1451 string gdcmHeader::GetElValRepByName(string TagName) {
1452 string pub = GetPubElValRepByName(TagName);
1455 return GetShaElValRepByName(TagName);
1459 * \ingroup gdcmHeader
1460 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1461 * through it's (group, element) and modifies it's content with
1463 * @param content new value to substitute with
1464 * @param group group of the ElVal to modify
1465 * @param element element of the ElVal to modify
1467 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1470 //TODO : homogeneiser les noms : SetPubElValByNumber qui appelle PubElValSet.SetElValueByNumber
1471 // pourquoi pas SetPubElValueByNumber ??
1474 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1478 * \ingroup gdcmHeader
1479 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1480 * through tag name and modifies it's content with the given value.
1481 * @param content new value to substitute with
1482 * @param TagName name of the tag to be modified
1484 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1485 return ( PubElValSet.SetElValueByName (content, TagName) );
1489 * \ingroup gdcmHeader
1490 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1491 * through it's (group, element) and modifies it's length with
1493 * \warning Use with extreme caution.
1494 * @param length new length to substitute with
1495 * @param group group of the ElVal to modify
1496 * @param element element of the ElVal to modify
1497 * @return 1 on success, 0 otherwise.
1500 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1502 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1506 * \ingroup gdcmHeader
1507 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1508 * through it's (group, element) and modifies it's content with
1510 * @param content new value to substitute with
1511 * @param group group of the ElVal to modify
1512 * @param element element of the ElVal to modify
1513 * @return 1 on success, 0 otherwise.
1515 int gdcmHeader::SetShaElValByNumber(string content,
1516 guint16 group, guint16 element) {
1517 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1521 * \ingroup gdcmHeader
1522 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1523 * through tag name and modifies it's content with the given value.
1524 * @param content new value to substitute with
1525 * @param TagName name of the tag to be modified
1527 int gdcmHeader::SetShaElValByName(string content, string TagName) {
1528 return ( ShaElValSet.SetElValueByName (content, TagName) );
1532 * \ingroup gdcmHeader
1533 * \brief Parses the header of the file but WITHOUT loading element values.
1535 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1536 gdcmElValue * newElValue = (gdcmElValue *)0;
1540 while ( (newElValue = ReadNextElement()) ) {
1541 SkipElementValue(newElValue);
1542 PubElValSet.Add(newElValue);
1549 // des que les element values sont chargees, stocker,
1550 // en une seule fois, dans des entiers
1551 // NX, NY, NZ, Bits allocated, Bits Stored, High Bit, Samples Per Pixel
1552 // (TODO : preciser les autres)
1553 // et refaire ceux des accesseurs qui renvoient les entiers correspondants
1555 // --> peut etre dangereux ?
1556 // si l'utilisateur modifie 'manuellement' l'un des paramètres
1557 // l'entier de sera pas modifié ...
1558 // (pb de la mise à jour en cas de redondance :-(
1561 * \ingroup gdcmHeader
1562 * \brief Retrieve the number of columns of image.
1563 * @return The encountered size when found, 0 by default.
1565 int gdcmHeader::GetXSize(void) {
1566 // We cannot check for "Columns" because the "Columns" tag is present
1567 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1568 string StrSize = GetPubElValByNumber(0x0028,0x0011);
1569 if (StrSize == "gdcm::Unfound")
1571 return atoi(StrSize.c_str());
1575 * \ingroup gdcmHeader
1576 * \brief Retrieve the number of lines of image.
1577 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1578 * @return The encountered size when found, 1 by default.
1580 int gdcmHeader::GetYSize(void) {
1581 // We cannot check for "Rows" because the "Rows" tag is present
1582 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1583 string StrSize = GetPubElValByNumber(0x0028,0x0010);
1584 if (StrSize != "gdcm::Unfound")
1585 return atoi(StrSize.c_str());
1589 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1590 // hence be a signal (1d image). So we default to 1:
1595 * \ingroup gdcmHeader
1596 * \brief Retrieve the number of planes of volume or the number
1597 * of frames of a multiframe.
1598 * \warning When present we consider the "Number of Frames" as the third
1599 * dimension. When absent we consider the third dimension as
1600 * being the "Planes" tag content.
1601 * @return The encountered size when found, 1 by default.
1603 int gdcmHeader::GetZSize(void) {
1604 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1605 // as the third dimension.
1606 string StrSize = GetPubElValByNumber(0x0028,0x0008);
1607 if (StrSize != "gdcm::Unfound")
1608 return atoi(StrSize.c_str());
1610 // We then consider the "Planes" entry as the third dimension [we
1611 // cannot retrieve by name since "Planes tag is present both in
1612 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1613 StrSize = GetPubElValByNumber(0x0028,0x0012);
1614 if (StrSize != "gdcm::Unfound")
1615 return atoi(StrSize.c_str());
1621 * \ingroup gdcmHeader
1622 * \brief Retrieve the number of Bits Stored
1623 * (as opposite to number of Bits Allocated)
1625 * @return The encountered number of Bits Stored, 0 by default.
1627 int gdcmHeader::GetBitsStored(void) {
1628 string StrSize = GetPubElValByNumber(0x0028,0x0101);
1629 if (StrSize == "gdcm::Unfound")
1631 return atoi(StrSize.c_str());
1636 * \ingroup gdcmHeader
1637 * \brief Retrieve the number of Samples Per Pixel
1638 * (1 : gray level, 3 : RGB)
1640 * @return The encountered number of Samples Per Pixel, 1 by default.
1642 int gdcmHeader::GetSamplesPerPixel(void) {
1643 string StrSize = GetPubElValByNumber(0x0028,0x0002);
1644 if (StrSize == "gdcm::Unfound")
1645 return 1; // Well, it's supposed to be mandatory ...
1646 return atoi(StrSize.c_str());
1649 * \ingroup gdcmHeader
1650 * \brief Return the size (in bytes) of a single pixel of data.
1651 * @return The size in bytes of a single pixel of data.
1654 int gdcmHeader::GetPixelSize(void) {
1655 string PixelType = GetPixelType();
1656 if (PixelType == "8U" || PixelType == "8S")
1658 if (PixelType == "16U" || PixelType == "16S")
1660 if (PixelType == "32U" || PixelType == "32S")
1662 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1667 * \ingroup gdcmHeader
1668 * \brief Build the Pixel Type of the image.
1669 * Possible values are:
1670 * - 8U unsigned 8 bit,
1671 * - 8S signed 8 bit,
1672 * - 16U unsigned 16 bit,
1673 * - 16S signed 16 bit,
1674 * - 32U unsigned 32 bit,
1675 * - 32S signed 32 bit,
1676 * \warning 12 bit images appear as 16 bit.
1679 string gdcmHeader::GetPixelType(void) {
1681 BitsAlloc = GetElValByName("Bits Allocated");
1682 if (BitsAlloc == "gdcm::Unfound") {
1683 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1684 BitsAlloc = string("16");
1686 if (BitsAlloc == "12")
1687 BitsAlloc = string("16");
1690 Signed = GetElValByName("Pixel Representation");
1691 if (Signed == "gdcm::Unfound") {
1692 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1693 BitsAlloc = string("0");
1696 Signed = string("U");
1698 Signed = string("S");
1700 return( BitsAlloc + Signed);
1705 * \ingroup gdcmHeader
1706 * \brief This predicate, based on hopefully reasonnable heuristics,
1707 * decides whether or not the current gdcmHeader was properly parsed
1708 * and contains the mandatory information for being considered as
1709 * a well formed and usable image.
1710 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1713 bool gdcmHeader::IsReadable(void) {
1714 if ( GetElValByName("Image Dimensions") != "gdcm::Unfound"
1715 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1718 if ( GetElValByName("Bits Allocated") == "gdcm::Unfound" )
1720 if ( GetElValByName("Bits Stored") == "gdcm::Unfound" )
1722 if ( GetElValByName("High Bit") == "gdcm::Unfound" )
1724 if ( GetElValByName("Pixel Representation") == "gdcm::Unfound" )
1730 * \ingroup gdcmHeader
1731 * \brief Small utility function that creates a new manually crafted
1732 * (as opposed as read from the file) gdcmElValue with user
1733 * specified name and adds it to the public tag hash table.
1734 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1735 * @param NewTagName The name to be given to this new tag.
1736 * @param VR The Value Representation to be given to this new tag.
1737 * @ return The newly hand crafted Element Value.
1739 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1740 gdcmElValue* NewElVal = (gdcmElValue*)0;
1741 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1742 guint32 FreeElem = 0;
1743 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1745 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1746 if (FreeElem == UINT32_MAX) {
1747 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1748 "Group 0xffff in Public Dict is full");
1749 return (gdcmElValue*)0;
1751 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1752 VR, "GDCM", NewTagName);
1753 NewElVal = new gdcmElValue(NewEntry);
1754 PubElValSet.Add(NewElVal);
1759 * \ingroup gdcmHeader
1760 * \brief Loads the element values of all the elements present in the
1761 * public tag based hash table.
1763 void gdcmHeader::LoadElements(void) {
1765 TagElValueHT ht = PubElValSet.GetTagHt();
1766 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1767 LoadElementValue(tag->second);
1772 * \ingroup gdcmHeader
1776 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1777 PubElValSet.Print(os);
1781 * \ingroup gdcmHeader
1785 void gdcmHeader::PrintPubDict(std::ostream & os) {
1786 RefPubDict->Print(os);
1790 * \ingroup gdcmHeader
1795 int gdcmHeader::Write(FILE * fp, FileType type) {
1796 return PubElValSet.Write(fp, type);
1800 * \ingroup gdcmHeader
1804 float gdcmHeader::GetXSpacing(void) {
1805 float xspacing, yspacing;
1806 string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1808 if (StrSpacing == "gdcm::Unfound") {
1809 dbg.Verbose(0, "gdcmHeader::GetXSpacing: unfound Pixel Spacing");
1812 if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1819 * \ingroup gdcmHeader
1823 float gdcmHeader::GetYSpacing(void) {
1824 float xspacing, yspacing;
1825 string StrSpacing = GetPubElValByNumber(0x0028,0x0030);
1827 if (StrSpacing == "gdcm::Unfound") {
1828 dbg.Verbose(0, "gdcmHeader::GetYSpacing: unfound Pixel Spacing");
1832 if( sscanf( StrSpacing.c_str(), "%f\\%f", &xspacing, &yspacing) != 2)
1837 dbg.Verbose(0, "gdcmHeader::GetYSpacing: gdcmData/CT-MONO2-8-abdo.dcm problem");
1838 // seems to be a bug in the header ...
1839 sscanf( StrSpacing.c_str(), "%f\\0\\%f", &xspacing, &yspacing);
1846 * \ingroup gdcmHeader
1850 float gdcmHeader::GetZSpacing(void) {
1851 // TODO : translate into English
1852 // Spacing Between Slices : distance entre le milieu de chaque coupe
1853 // Les coupes peuvent etre :
1854 // jointives (Spacing between Slices = Slice Thickness)
1855 // chevauchantes (Spacing between Slices < Slice Thickness)
1856 // disjointes (Spacing between Slices > Slice Thickness)
1857 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
1858 // ca interesse le physicien de l'IRM, pas le visualisateur de volumes ...
1859 // Si le Spacing Between Slices est absent,
1860 // on suppose que les coupes sont jointives
1862 string StrSpacingBSlices = GetPubElValByNumber(0x0018,0x0088);
1864 if (StrSpacingBSlices == "gdcm::Unfound") {
1865 dbg.Verbose(0, "gdcmHeader::GetZSpacing: unfound StrSpacingBSlices");
1866 string StrSliceThickness = GetPubElValByNumber(0x0018,0x0050);
1867 if (StrSliceThickness == "gdcm::Unfound")
1870 return atof(StrSliceThickness.c_str());
1872 return atof(StrSpacingBSlices.c_str());
1877 // Image Position Patient :
1878 // If not found (AVR-NEMA), we consider Slice Location (20,1041)
1879 // or Location (20,50) as the Z coordinate,
1880 // 0. for all the coordinates if Slice Location not found
1881 // TODO : find a way to inform the caller nothing was found
1882 // TODO : How to tell the caller a wrong number of values was found?
1884 * \ingroup gdcmHeader
1888 float gdcmHeader::GetXImagePosition(void) {
1889 float xImPos, yImPos, zImPos;
1890 // 0020,0032 : Image Position Patient
1891 // 0020,1041 : Slice Location
1892 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1894 if (StrImPos == "gdcm::Unfound") {
1895 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Image Position Patient");
1896 string StrSliceLoc = GetPubElValByNumber(0x0020,0x1041);
1897 if (StrSliceLoc == "gdcm::Unfound") {
1898 dbg.Verbose(0, "gdcmHeader::GetXImagePosition: unfound Slice Location");
1899 // How to tell the caller nothing was found?
1903 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1904 // How to tell the caller a wrong number of values was found?
1911 * \ingroup gdcmHeader
1915 float gdcmHeader::GetYImagePosition(void) {
1916 float xImPos, yImPos, zImPos;
1917 // 0020,0032 : Image Position Patient
1918 // 0020,1041 : Slice Location
1919 // 0020,0050 : Location
1920 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1922 if (StrImPos == "gdcm::Unfound") {
1923 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position Patient");
1924 string StrSliceLoc = GetPubElValByNumber(0x0020,0x1041);
1925 if (StrSliceLoc == "gdcm::Unfound") {
1926 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
1927 // How to tell the caller nothing was found?
1928 string StrLocation = GetPubElValByNumber(0x0020,0x0050);
1929 if (StrSliceLoc == "gdcm::Unfound") {
1930 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
1935 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3)
1936 // How to tell the caller a wrong number of values was found?
1943 * \ingroup gdcmHeader
1947 float gdcmHeader::GetZImagePosition(void) {
1948 float xImPos, yImPos, zImPos;
1949 // 0020,0032 : Image Position Patient
1950 // 0020,1041 : Slice Location
1951 // 0020,0050 : Location
1953 // TODO : How to tell the caller nothing was found?
1954 // TODO : How to tell the caller a wrong number of values was found?
1956 string StrImPos = GetPubElValByNumber(0x0020,0x0032);
1957 if (StrImPos != "gdcm::Unfound") {
1958 if( sscanf( StrImPos.c_str(), "%f\\%f\\%f", &xImPos, &yImPos, &zImPos) != 3) {
1959 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Image Position Patient");
1960 return 0.; // bug in the element 0x0020,0x0032
1965 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Image Position Patient");
1967 string StrSliceLocation = GetPubElValByNumber(0x0020,0x1041);
1968 if (StrSliceLocation != "gdcm::Unfound") {
1969 if( sscanf( StrSliceLocation.c_str(), "%f", &zImPos) !=1) {
1970 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Slice Location");
1971 return 0.; // bug in the element 0x0020,0x1041
1976 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
1978 string StrLocation = GetPubElValByNumber(0x0020,0x0050);
1979 if (StrLocation != "gdcm::Unfound") {
1980 if( sscanf( StrLocation.c_str(), "%f", &zImPos) !=1) {
1981 dbg.Verbose(0, "gdcmHeader::GetZImagePosition: wrong Location");
1982 return 0.; // bug in the element 0x0020,0x0050
1987 dbg.Verbose(0, "gdcmHeader::GetYImagePosition: unfound Slice Location");
1989 return 0.; // Hopeless