1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.94 2003/10/03 16:22:24 jpr Exp $
3 #include "gdcmHeader.h"
11 #include <netinet/in.h>
13 #include <cctype> // for isalpha
18 // Refer to gdcmHeader::CheckSwap()
19 #define HEADER_LENGTH_TO_READ 256
20 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
21 //#define _MaxSizeLoadElementValue_ 1024
22 #define _MaxSizeLoadElementValue_ 4096
27 void gdcmHeader::Initialise(void) {
28 dicom_vr = gdcmGlobal::GetVR();
29 dicom_ts = gdcmGlobal::GetTS();
30 Dicts = gdcmGlobal::GetDicts();
31 RefPubDict = Dicts->GetDefaultPubDict();
32 RefShaDict = (gdcmDict*)0;
39 * @param exception_on_error
41 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) {
42 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
43 filename = InFilename;
45 if ( !OpenFile(exception_on_error))
55 * @param exception_on_error
57 gdcmHeader::gdcmHeader(bool exception_on_error) {
58 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
65 * @param exception_on_error
68 bool gdcmHeader::OpenFile(bool exception_on_error)
69 throw(gdcmFileError) {
70 fp=fopen(filename.c_str(),"rb");
71 if(exception_on_error) {
73 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
77 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
84 * @return TRUE if the close was successfull
86 bool gdcmHeader::CloseFile(void) {
87 int closed = fclose(fp);
96 * \brief Canonical destructor.
98 gdcmHeader::~gdcmHeader (void) {
99 dicom_vr = (gdcmVR*)0;
100 Dicts = (gdcmDictSet*)0;
101 RefPubDict = (gdcmDict*)0;
102 RefShaDict = (gdcmDict*)0;
108 // ---> Warning : This fourth fiels is NOT part
109 // of the 'official' Dicom Dictionnary
110 // and should NOT be used.
111 // (Not defined for all the groups
112 // may be removed in a future release)
115 // META Meta Information
127 // NMI Nuclear Medicine
129 // BFS Basic Film Session
130 // BFB Basic Film Box
131 // BIB Basic Image Box
147 * \ingroup gdcmHeader
148 * \brief Discover what the swap code is (among little endian, big endian,
149 * bad little endian, bad big endian).
152 void gdcmHeader::CheckSwap()
154 // The only guaranted way of finding the swap code is to find a
155 // group tag since we know it's length has to be of four bytes i.e.
156 // 0x00000004. Finding the swap code in then straigthforward. Trouble
157 // occurs when we can't find such group...
159 guint32 x=4; // x : for ntohs
160 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
164 char deb[HEADER_LENGTH_TO_READ];
166 // First, compare HostByteOrder and NetworkByteOrder in order to
167 // determine if we shall need to swap bytes (i.e. the Endian type).
173 // The easiest case is the one of a DICOM header, since it possesses a
174 // file preamble where it suffice to look for the string "DICM".
175 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
178 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
179 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
180 // Next, determine the value representation (VR). Let's skip to the
181 // first element (0002, 0000) and check there if we find "UL"
182 // - or "OB" if the 1st one is (0002,0001) -,
183 // in which case we (almost) know it is explicit VR.
184 // WARNING: if it happens to be implicit VR then what we will read
185 // is the length of the group. If this ascii representation of this
186 // length happens to be "UL" then we shall believe it is explicit VR.
187 // FIXME: in order to fix the above warning, we could read the next
188 // element value (or a couple of elements values) in order to make
189 // sure we are not commiting a big mistake.
191 // * the 128 bytes of File Preamble (often padded with zeroes),
192 // * the 4 bytes of "DICM" string,
193 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
194 // i.e. a total of 136 bytes.
197 // Use gdcmHeader::dicom_vr to test all the possibilities
198 // instead of just checking for UL, OB and UI !?
199 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
200 (memcmp(entCur, "OB", (size_t)2) == 0) ||
201 (memcmp(entCur, "UI", (size_t)2) == 0) )
203 filetype = ExplicitVR;
204 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
205 "explicit Value Representation");
207 filetype = ImplicitVR;
208 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
209 "not an explicit Value Representation");
213 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
214 "HostByteOrder != NetworkByteOrder");
217 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
218 "HostByteOrder = NetworkByteOrder");
221 // Position the file position indicator at first tag (i.e.
222 // after the file preamble and the "DICM" string).
224 fseek (fp, 132L, SEEK_SET);
228 // Alas, this is not a DicomV3 file and whatever happens there is no file
229 // preamble. We can reset the file position indicator to where the data
230 // is (i.e. the beginning of the file).
231 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
234 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
235 // By clean we mean that the length of the first tag is written down.
236 // If this is the case and since the length of the first group HAS to be
237 // four (bytes), then determining the proper swap code is straightforward.
240 // We assume the array of char we are considering contains the binary
241 // representation of a 32 bits integer. Hence the following dirty
243 s = *((guint32 *)(entCur));
263 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
264 "ACR/NEMA unfound swap info (time to raise bets)");
267 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
268 // It is time for despaired wild guesses. So, let's assume this file
269 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
270 // not present. Then the only info we have is the net2host one.
280 * \ingroup gdcmHeader
283 void gdcmHeader::SwitchSwapToBigEndian(void) {
284 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
285 "Switching to BigEndian mode.");
303 * \ingroup gdcmHeader
304 * \brief Find the value representation of the current tag.
307 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
308 if (filetype != ExplicitVR)
314 char msg[100]; // for sprintf. Sorry
316 long PositionOnEntry = ftell(fp);
317 // Warning: we believe this is explicit VR (Value Representation) because
318 // we used a heuristic that found "UL" in the first tag. Alas this
319 // doesn't guarantee that all the tags will be in explicit VR. In some
320 // cases (see e-film filtered files) one finds implicit VR tags mixed
321 // within an explicit VR file. Hence we make sure the present tag
322 // is in explicit VR and try to fix things if it happens not to be
324 bool RealExplicit = true;
326 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
328 vr = std::string(VR);
330 // Assume we are reading a falsely explicit VR file i.e. we reached
331 // a tag where we expect reading a VR but are in fact we read the
332 // first to bytes of the length. Then we will interogate (through find)
333 // the dicom_vr dictionary with oddities like "\004\0" which crashes
334 // both GCC and VC++ implementations of the STL map. Hence when the
335 // expected VR read happens to be non-ascii characters we consider
336 // we hit falsely explicit VR tag.
338 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
339 RealExplicit = false;
341 // CLEANME searching the dicom_vr at each occurence is expensive.
342 // PostPone this test in an optional integrity check at the end
343 // of parsing or only in debug mode.
344 if ( RealExplicit && !dicom_vr->Count(vr) )
347 if ( RealExplicit ) {
348 if ( ElVal->IsVrUnknown() ) {
349 // When not a dictionary entry, we can safely overwrite the vr.
353 if ( ElVal->GetVR() == vr ) {
354 // The vr we just read and the dictionary agree. Nothing to do.
357 // The vr present in the file and the dictionary disagree. We assume
358 // the file writer knew best and use the vr of the file. Since it would
359 // be unwise to overwrite the vr of a dictionary (since it would
360 // compromise it's next user), we need to clone the actual DictEntry
361 // and change the vr for the read one.
362 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
367 ElVal->SetDictEntry(NewTag);
371 // We thought this was explicit VR, but we end up with an
372 // implicit VR tag. Let's backtrack.
374 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
375 ElVal->GetGroup(),ElVal->GetElement());
376 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
378 fseek(fp, PositionOnEntry, SEEK_SET);
379 // When this element is known in the dictionary we shall use, e.g. for
380 // the semantics (see the usage of IsAnInteger), the vr proposed by the
381 // dictionary entry. Still we have to flag the element as implicit since
382 // we know now our assumption on expliciteness is not furfilled.
384 if ( ElVal->IsVrUnknown() )
385 ElVal->SetVR("Implicit");
386 ElVal->SetImplicitVr();
390 * \ingroup gdcmHeader
391 * \brief Determines if the Transfer Syntax was already encountered
392 * and if it corresponds to a ImplicitVRLittleEndian one.
394 * @return True when ImplicitVRLittleEndian found. False in all other cases.
396 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
397 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
400 LoadElementValueSafe(Element);
401 std::string Transfer = Element->GetValue();
402 if ( Transfer == "1.2.840.10008.1.2" )
408 * \ingroup gdcmHeader
409 * \brief Determines if the Transfer Syntax was already encountered
410 * and if it corresponds to a ExplicitVRLittleEndian one.
412 * @return True when ExplicitVRLittleEndian found. False in all other cases.
414 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
415 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
418 LoadElementValueSafe(Element);
419 std::string Transfer = Element->GetValue();
420 if ( Transfer == "1.2.840.10008.1.2.1" )
426 * \ingroup gdcmHeader
427 * \brief Determines if the Transfer Syntax was already encountered
428 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
430 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
432 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
433 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
436 LoadElementValueSafe(Element);
437 std::string Transfer = Element->GetValue();
438 if ( Transfer == "1.2.840.10008.1.2.1.99" )
444 * \ingroup gdcmHeader
445 * \brief Determines if the Transfer Syntax was already encountered
446 * and if it corresponds to a Explicit VR Big Endian one.
448 * @return True when big endian found. False in all other cases.
450 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
451 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
454 LoadElementValueSafe(Element);
455 std::string Transfer = Element->GetValue();
456 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
462 * \ingroup gdcmHeader
463 * \brief Determines if the Transfer Syntax was already encountered
464 * and if it corresponds to a JPEGBaseLineProcess1 one.
466 * @return True when JPEGBaseLineProcess1found. False in all other cases.
468 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
469 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
472 LoadElementValueSafe(Element);
473 std::string Transfer = Element->GetValue();
474 if ( Transfer == "1.2.840.10008.1.2.4.50" )
480 * \ingroup gdcmHeader
485 bool gdcmHeader::IsJPEGLossless(void) {
486 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
487 // faire qq chose d'intelligent a la place de ça
490 LoadElementValueSafe(Element);
491 const char * Transfert = Element->GetValue().c_str();
492 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
493 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
494 if (Element->GetValue() == "1.2.840.10008.1.2.4.57") return true;
501 * \ingroup gdcmHeader
502 * \brief Determines if the Transfer Syntax was already 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 std::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 already 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 std::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 already 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 std::string Transfer = Element->GetValue();
550 if ( Transfer == "1.2.840.10008.1.2.4.53" )
556 * \ingroup gdcmHeader
557 * \brief Determines if the Transfer Syntax was already encountered
558 * and if it corresponds to a RLE Lossless one.
560 * @return True when RLE Lossless found. False in all
563 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
564 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
567 LoadElementValueSafe(Element);
568 std::string Transfer = Element->GetValue();
569 if ( Transfer == "1.2.840.10008.1.2.5" )
575 * \ingroup gdcmHeader
576 * \brief Determines if the Transfer Syntax was already encountered
577 * and if it corresponds to a JPEG200 one.0
579 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
582 bool gdcmHeader::IsJPEG2000(void) {
583 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
586 LoadElementValueSafe(Element);
587 std::string Transfer = Element->GetValue();
588 if ( (Transfer == "1.2.840.10008.1.2.4.90")
589 || (Transfer == "1.2.840.10008.1.2.4.91") )
595 * \ingroup gdcmHeader
596 * \brief Predicate for dicom version 3 file.
597 * @return True when the file is a dicom version 3.
599 bool gdcmHeader::IsDicomV3(void) {
600 if ( (filetype == ExplicitVR)
601 || (filetype == ImplicitVR) )
607 * \ingroup gdcmHeader
608 * \brief When the length of an element value is obviously wrong (because
609 * the parser went Jabberwocky) one can hope improving things by
610 * applying this heuristic.
612 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
613 if ( FoundLength == 0xffffffff)
615 ElVal->SetLength(FoundLength);
619 * \ingroup gdcmHeader
624 guint32 gdcmHeader::FindLengthOB(void) {
625 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
628 long PositionOnEntry = ftell(fp);
629 bool FoundSequenceDelimiter = false;
630 guint32 TotalLength = 0;
633 while ( ! FoundSequenceDelimiter) {
641 TotalLength += 4; // We even have to decount the group and element
643 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
644 char msg[100]; // for sprintf. Sorry
645 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
646 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
651 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
652 FoundSequenceDelimiter = true;
653 else if ( n != 0xe000 ){
654 char msg[100]; // for sprintf. Sorry
655 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
657 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
661 ItemLength = ReadInt32();
662 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
663 // the ItemLength with ReadInt32
665 SkipBytes(ItemLength);
667 fseek(fp, PositionOnEntry, SEEK_SET);
672 * \ingroup gdcmHeader
677 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
678 guint16 element = ElVal->GetElement();
679 guint16 group = ElVal->GetGroup();
680 std::string vr = ElVal->GetVR();
682 if( (element == 0x0010) && (group == 0x7fe0) ) {
684 dbg.Verbose(2, "gdcmHeader::FindLength: ",
685 "we reached 7fe0 0010");
688 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
689 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
691 // The following reserved two bytes (see PS 3.5-2001, section
692 // 7.1.2 Data element structure with explicit vr p27) must be
693 // skipped before proceeding on reading the length on 4 bytes.
694 fseek(fp, 2L, SEEK_CUR);
696 guint32 length32 = ReadInt32();
697 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
698 ElVal->SetLength(FindLengthOB());
701 FixFoundLength(ElVal, length32);
705 // Length is encoded on 2 bytes.
706 length16 = ReadInt16();
708 // We can tell the current file is encoded in big endian (like
709 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
710 // and it's value is the one of the encoding of a big endian file.
711 // In order to deal with such big endian encoded files, we have
712 // (at least) two strategies:
713 // * when we load the "Transfer Syntax" tag with value of big endian
714 // encoding, we raise the proper flags. Then we wait for the end
715 // of the META group (0x0002) among which is "Transfer Syntax",
716 // before switching the swap code to big endian. We have to postpone
717 // the switching of the swap code since the META group is fully encoded
718 // in little endian, and big endian coding only starts at the next
719 // group. The corresponding code can be hard to analyse and adds
720 // many additional unnecessary tests for regular tags.
721 // * the second strategy consists in waiting for trouble, that shall
722 // appear when we find the first group with big endian encoding. This
723 // is easy to detect since the length of a "Group Length" tag (the
724 // ones with zero as element number) has to be of 4 (0x0004). When we
725 // encouter 1024 (0x0400) chances are the encoding changed and we
726 // found a group with big endian encoding.
727 // We shall use this second strategy. In order to make sure that we
728 // can interpret the presence of an apparently big endian encoded
729 // length of a "Group Length" without committing a big mistake, we
730 // add an additional check: we look in the already parsed elements
731 // for the presence of a "Transfer Syntax" whose value has to be "big
732 // endian encoding". When this is the case, chances are we have got our
733 // hands on a big endian encoded file: we switch the swap code to
734 // big endian and proceed...
735 if ( (element == 0x0000) && (length16 == 0x0400) ) {
736 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
737 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
742 SwitchSwapToBigEndian();
743 // Restore the unproperly loaded values i.e. the group, the element
744 // and the dictionary entry depending on them.
745 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
746 guint16 CorrectElem = SwapShort(ElVal->GetElement());
747 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
750 // This correct tag is not in the dictionary. Create a new one.
751 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
753 // FIXME this can create a memory leaks on the old entry that be
754 // left unreferenced.
755 ElVal->SetDictEntry(NewTag);
758 // Heuristic: well some files are really ill-formed.
759 if ( length16 == 0xffff) {
761 dbg.Verbose(0, "gdcmHeader::FindLength",
762 "Erroneous element length fixed.");
764 FixFoundLength(ElVal, (guint32)length16);
768 // Either implicit VR or a non DICOM conformal (see not below) explicit
769 // VR that ommited the VR of (at least) this element. Farts happen.
770 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
771 // on Data elements "Implicit and Explicit VR Data Elements shall
772 // not coexist in a Data Set and Data Sets nested within it".]
773 // Length is on 4 bytes.
774 FixFoundLength(ElVal, ReadInt32());
778 * \ingroup gdcmHeader
779 * \brief Swaps back the bytes of 4-byte long integer accordingly to
782 * @return The suggested integer.
784 guint32 gdcmHeader::SwapLong(guint32 a) {
789 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
790 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
794 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
798 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
801 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
808 * \ingroup gdcmHeader
809 * \brief Swaps the bytes so they agree with the processor order
810 * @return The properly swaped 16 bits integer.
812 guint16 gdcmHeader::SwapShort(guint16 a) {
813 if ( (sw==4321) || (sw==2143) )
814 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
819 * \ingroup gdcmHeader
824 void gdcmHeader::SkipBytes(guint32 NBytes) {
825 //FIXME don't dump the returned value
826 (void)fseek(fp, (long)NBytes, SEEK_CUR);
830 * \ingroup gdcmHeader
835 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
836 SkipBytes(ElVal->GetLength());
840 * \ingroup gdcmHeader
845 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
848 if ((guint32)NewSize >= (guint32)0xffffffff) {
849 MaxSizeLoadElementValue = 0xffffffff;
852 MaxSizeLoadElementValue = NewSize;
856 * \ingroup gdcmHeader
857 * \brief Loads the element content if it's length is not bigger
858 * than the value specified with
859 * gdcmHeader::SetMaxSizeLoadElementValue()
861 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
863 guint16 group = ElVal->GetGroup();
864 std::string vr= ElVal->GetVR();
865 guint32 length = ElVal->GetLength();
866 bool SkipLoad = false;
868 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
870 // FIXME Sequences not treated yet !
872 // Ne faudrait-il pas au contraire trouver immediatement
873 // une maniere 'propre' de traiter les sequences (vr = SQ)
874 // car commencer par les ignorer risque de conduire a qq chose
875 // qui pourrait ne pas etre generalisable
876 // Well, I'm expecting your code !!!
881 // Heuristic : a sequence "contains" a set of tags (called items). It looks
882 // like the last tag of a sequence (the one that terminates the sequence)
883 // has a group of 0xfffe (with a dummy length).
885 // Actually (fffe e000) tells us an Element is beginning
886 // (fffe e00d) tells us an Element just ended
887 // (fffe e0dd) tells us the current SEQuence just ended
889 if( group == 0xfffe )
894 ElVal->SetValue("gdcm::Skipped");
898 // When the length is zero things are easy:
904 // The elements whose length is bigger than the specified upper bound
905 // are not loaded. Instead we leave a short notice of the offset of
906 // the element content and it's length.
907 if (length > MaxSizeLoadElementValue) {
908 std::ostringstream s;
909 s << "gdcm::NotLoaded.";
910 s << " Address:" << (long)ElVal->GetOffset();
911 s << " Length:" << ElVal->GetLength();
912 ElVal->SetValue(s.str());
916 // When an integer is expected, read and convert the following two or
917 // four bytes properly i.e. as an integer as opposed to a string.
919 // pour les elements de Value Multiplicity > 1
920 // on aura en fait une serie d'entiers
921 // on devrait pouvoir faire + compact (?)
923 if ( IsAnInteger(ElVal) ) {
925 std::ostringstream s;
927 if (vr == "US" || vr == "SS") {
929 NewInt = ReadInt16();
932 for (int i=1; i < nbInt; i++) {
934 NewInt = ReadInt16();
939 } else if (vr == "UL" || vr == "SL") {
941 NewInt = ReadInt32();
944 for (int i=1; i < nbInt; i++) {
946 NewInt = ReadInt32();
951 ElVal->SetValue(s.str());
955 // We need an additional byte for storing \0 that is not on disk
956 char* NewValue = (char*)malloc(length+1);
958 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
963 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
964 if ( item_read != 1 ) {
966 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
967 ElVal->SetValue("gdcm::UnRead");
970 ElVal->SetValue(NewValue);
975 * \ingroup gdcmHeader
976 * \brief Loads the element while preserving the current
977 * underlying file position indicator as opposed to
978 * to LoadElementValue that modifies it.
979 * @param ElVal Element whose value shall be loaded.
982 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
983 long PositionOnEntry = ftell(fp);
984 LoadElementValue(ElVal);
985 fseek(fp, PositionOnEntry, SEEK_SET);
989 * \ingroup gdcmHeader
990 * \brief Reads a supposed to be 16 Bits integer
991 * \ (swaps it depending on processor endianity)
993 * @return integer acts as a boolean
995 guint16 gdcmHeader::ReadInt16(void) {
998 item_read = fread (&g, (size_t)2,(size_t)1, fp);
999 if ( item_read != 1 ) {
1000 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1002 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1004 dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1014 * \ingroup gdcmHeader
1015 * \brief Reads a supposed to be 32 Bits integer
1016 * \ (swaps it depending on processor endianity)
1020 guint32 gdcmHeader::ReadInt32(void) {
1023 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1024 if ( item_read != 1 ) {
1025 //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1027 // dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1029 dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");
1039 * \ingroup gdcmHeader
1044 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1046 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1048 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1049 "failed to Locate gdcmElValue");
1050 return (gdcmElValue*)0;
1056 * \ingroup gdcmHeader
1057 * \brief Build a new Element Value from all the low level arguments.
1058 * Check for existence of dictionary entry, and build
1059 * a default one when absent.
1060 * @param Group group of the underlying DictEntry
1061 * @param Elem element of the underlying DictEntry
1063 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1064 // Find out if the tag we encountered is in the dictionaries:
1065 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1067 NewTag = new gdcmDictEntry(Group, Elem);
1069 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1071 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1072 "failed to allocate gdcmElValue");
1073 return (gdcmElValue*)0;
1079 * \ingroup gdcmHeader
1084 * \return integer acts as a boolean
1086 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value,
1087 guint16 Group, guint16 Elem ) {
1089 // TODO : FIXME JPRx
1091 // on (je) cree une Elvalue ne contenant pas de valeur
1092 // on l'ajoute au ElValSet
1093 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1094 // --> devrait pouvoir etre fait + simplement ???
1096 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1097 PubElValSet.Add(nvElValue);
1098 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1104 * \ingroup gdcmHeader
1105 * \brief Modify (or Creates if not found) an element
1106 * @param Value new value
1109 * \return integer acts as a boolean
1112 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1114 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1115 PubElValSet.Add(nvElValue);
1116 std::string v = Value;
1117 PubElValSet.SetElValueByNumber(v, Group, Elem);
1123 * \ingroup gdcmHeader
1124 * \brief Set a new value if the invoked element exists
1128 * \return integer acts as a boolean
1130 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1132 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1133 std::string v = Value;
1134 PubElValSet.SetElValueByNumber(v, Group, Elem);
1140 * \ingroup gdcmHeader
1141 * \brief Checks if a given ElValue (group,number)
1142 * \ exists in the Public ElValSet
1145 * @return integer acts as a boolean
1148 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1149 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1153 * \ingroup gdcmHeader
1154 * \brief Build a new Element Value from all the low level arguments.
1155 * Check for existence of dictionary entry, and build
1156 * a default one when absent.
1157 * @param Name Name of the underlying DictEntry
1159 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1161 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1163 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1165 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1167 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1168 "failed to allocate gdcmElValue");
1169 return (gdcmElValue*)0;
1175 * \ingroup gdcmHeader
1176 * \brief Read the next tag but WITHOUT loading it's value
1177 * @return On succes the newly created ElValue, NULL on failure.
1179 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1182 gdcmElValue * NewElVal;
1188 // We reached the EOF (or an error occured) and header parsing
1189 // has to be considered as finished.
1190 return (gdcmElValue *)0;
1192 NewElVal = NewElValueByNumber(g, n);
1194 FindLength(NewElVal);
1197 return (gdcmElValue *)0;
1199 NewElVal->SetOffset(ftell(fp));
1200 //if ( (g==0x7fe0) && (n==0x0010) )
1205 * \ingroup gdcmHeader
1206 * \brief Apply some heuristics to predict wether the considered
1207 * element value contains/represents an integer or not.
1208 * @param ElVal The element value on which to apply the predicate.
1209 * @return The result of the heuristical predicate.
1211 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1212 guint16 group = ElVal->GetGroup();
1213 guint16 element = ElVal->GetElement();
1214 std::string vr = ElVal->GetVR();
1215 guint32 length = ElVal->GetLength();
1217 // When we have some semantics on the element we just read, and if we
1218 // a priori know we are dealing with an integer, then we shall be
1219 // able to swap it's element value properly.
1220 if ( element == 0 ) { // This is the group length of the group
1224 dbg.Error("gdcmHeader::IsAnInteger",
1225 "Erroneous Group Length element length.");
1228 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1235 * \ingroup gdcmHeader
1236 * \brief Recover the offset (from the beginning of the file) of the pixels.
1238 size_t gdcmHeader::GetPixelOffset(void) {
1239 // If this file complies with the norm we should encounter the
1240 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1241 // the group that contains the pixel data (hence the "Pixel Data"
1242 // is found by indirection through the "Image Location").
1243 // Inside the group pointed by "Image Location" the searched element
1244 // is conventionally the element 0x0010 (when the norm is respected).
1245 // When the "Image Location" is absent we default to group 0x7fe0.
1248 std::string ImageLocation = GetPubElValByName("Image Location");
1249 if ( ImageLocation == GDCM_UNFOUND ) {
1252 grPixel = (guint16) atoi( ImageLocation.c_str() );
1254 if (grPixel != 0x7fe0)
1255 // This is a kludge for old dirty Philips imager.
1260 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1263 return PixelElement->GetOffset();
1269 * \ingroup gdcmHeader
1270 * \brief Searches both the public and the shadow dictionary (when they
1271 * exist) for the presence of the DictEntry with given
1272 * group and element. The public dictionary has precedence on the
1274 * @param group group of the searched DictEntry
1275 * @param element element of the searched DictEntry
1276 * @return Corresponding DictEntry when it exists, NULL otherwise.
1278 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1280 gdcmDictEntry * found = (gdcmDictEntry*)0;
1281 if (!RefPubDict && !RefShaDict) {
1282 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1283 "we SHOULD have a default dictionary");
1286 found = RefPubDict->GetTagByNumber(group, element);
1291 found = RefShaDict->GetTagByNumber(group, element);
1299 * \ingroup gdcmHeader
1300 * \brief Searches both the public and the shadow dictionary (when they
1301 * exist) for the presence of the DictEntry with given name.
1302 * The public dictionary has precedence on the shadow one.
1303 * @param Name name of the searched DictEntry
1304 * @return Corresponding DictEntry when it exists, NULL otherwise.
1306 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1307 gdcmDictEntry * found = (gdcmDictEntry*)0;
1308 if (!RefPubDict && !RefShaDict) {
1309 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1310 "we SHOULD have a default dictionary");
1313 found = RefPubDict->GetTagByName(Name);
1318 found = RefShaDict->GetTagByName(Name);
1326 * \ingroup gdcmHeader
1327 * \brief Searches within the public dictionary for element value of
1329 * @param group Group of the researched tag.
1330 * @param element Element of the researched tag.
1331 * @return Corresponding element value when it exists, and the string
1332 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1334 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1335 return PubElValSet.GetElValueByNumber(group, element);
1339 * \ingroup gdcmHeader
1340 * \brief Searches within the public dictionary for element value
1341 * representation of a given tag.
1343 * Obtaining the VR (Value Representation) might be needed by caller
1344 * to convert the string typed content to caller's native type
1345 * (think of C++ vs Python). The VR is actually of a higher level
1346 * of semantics than just the native C++ type.
1347 * @param group Group of the researched tag.
1348 * @param element Element of the researched tag.
1349 * @return Corresponding element value representation when it exists,
1350 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1352 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1353 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1355 return GDCM_UNFOUND;
1356 return elem->GetVR();
1360 * \ingroup gdcmHeader
1361 * \brief Searches within the public dictionary for element value of
1363 * @param TagName name of the researched element.
1364 * @return Corresponding element value when it exists, and the string
1365 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1367 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1368 return PubElValSet.GetElValueByName(TagName);
1372 * \ingroup gdcmHeader
1373 * \brief Searches within the elements parsed with the public dictionary for
1374 * the element value representation of a given tag.
1376 * Obtaining the VR (Value Representation) might be needed by caller
1377 * to convert the string typed content to caller's native type
1378 * (think of C++ vs Python). The VR is actually of a higher level
1379 * of semantics than just the native C++ type.
1380 * @param TagName name of the researched element.
1381 * @return Corresponding element value representation when it exists,
1382 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1384 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1385 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1387 return GDCM_UNFOUND;
1388 return elem->GetVR();
1392 * \ingroup gdcmHeader
1393 * \brief Searches within elements parsed with the SHADOW dictionary
1394 * for the element value of a given tag.
1395 * @param group Group of the researched tag.
1396 * @param element Element of the researched tag.
1397 * @return Corresponding element value representation when it exists,
1398 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1400 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1401 return ShaElValSet.GetElValueByNumber(group, element);
1405 * \ingroup gdcmHeader
1406 * \brief Searches within the elements parsed with the SHADOW dictionary
1407 * for the element value representation of a given tag.
1409 * Obtaining the VR (Value Representation) might be needed by caller
1410 * to convert the string typed content to caller's native type
1411 * (think of C++ vs Python). The VR is actually of a higher level
1412 * of semantics than just the native C++ type.
1413 * @param group Group of the researched tag.
1414 * @param element Element of the researched tag.
1415 * @return Corresponding element value representation when it exists,
1416 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1418 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1419 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1421 return GDCM_UNFOUND;
1422 return elem->GetVR();
1426 * \ingroup gdcmHeader
1427 * \brief Searches within the elements parsed with the shadow dictionary
1428 * for an element value of given tag.
1429 * @param TagName name of the researched element.
1430 * @return Corresponding element value when it exists, and the string
1431 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1433 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1434 return ShaElValSet.GetElValueByName(TagName);
1438 * \ingroup gdcmHeader
1439 * \brief Searches within the elements parsed with the shadow dictionary for
1440 * the element value representation of a given tag.
1442 * Obtaining the VR (Value Representation) might be needed by caller
1443 * to convert the string typed content to caller's native type
1444 * (think of C++ vs Python). The VR is actually of a higher level
1445 * of semantics than just the native C++ type.
1446 * @param TagName name of the researched element.
1447 * @return Corresponding element value representation when it exists,
1448 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1450 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1451 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1453 return GDCM_UNFOUND;
1454 return elem->GetVR();
1458 * \ingroup gdcmHeader
1459 * \brief Searches within elements parsed with the public dictionary
1460 * and then within the elements parsed with the shadow dictionary
1461 * for the element value of a given tag.
1462 * @param group Group of the researched tag.
1463 * @param element Element of the researched tag.
1464 * @return Corresponding element value representation when it exists,
1465 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1467 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1468 std::string pub = GetPubElValByNumber(group, element);
1471 return GetShaElValByNumber(group, element);
1475 * \ingroup gdcmHeader
1476 * \brief Searches within elements parsed with the public dictionary
1477 * and then within the elements parsed with the shadow dictionary
1478 * for the element value representation of a given tag.
1480 * Obtaining the VR (Value Representation) might be needed by caller
1481 * to convert the string typed content to caller's native type
1482 * (think of C++ vs Python). The VR is actually of a higher level
1483 * of semantics than just the native C++ type.
1484 * @param group Group of the researched tag.
1485 * @param element Element of the researched tag.
1486 * @return Corresponding element value representation when it exists,
1487 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1489 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1490 std::string pub = GetPubElValRepByNumber(group, element);
1493 return GetShaElValRepByNumber(group, element);
1497 * \ingroup gdcmHeader
1498 * \brief Searches within elements parsed with the public dictionary
1499 * and then within the elements parsed with the shadow dictionary
1500 * for the element value of a given tag.
1501 * @param TagName name of the researched element.
1502 * @return Corresponding element value when it exists,
1503 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1505 std::string gdcmHeader::GetElValByName(std::string TagName) {
1506 std::string pub = GetPubElValByName(TagName);
1509 return GetShaElValByName(TagName);
1513 * \ingroup gdcmHeader
1514 * \brief Searches within elements parsed with the public dictionary
1515 * and then within the elements parsed with the shadow dictionary
1516 * for the element value representation of a given tag.
1518 * Obtaining the VR (Value Representation) might be needed by caller
1519 * to convert the string typed content to caller's native type
1520 * (think of C++ vs Python). The VR is actually of a higher level
1521 * of semantics than just the native C++ type.
1522 * @param TagName name of the researched element.
1523 * @return Corresponding element value representation when it exists,
1524 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1526 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1527 std::string pub = GetPubElValRepByName(TagName);
1530 return GetShaElValRepByName(TagName);
1534 * \ingroup gdcmHeader
1535 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1536 * through it's (group, element) and modifies it's content with
1538 * @param content new value to substitute with
1539 * @param group group of the ElVal to modify
1540 * @param element element of the ElVal to modify
1542 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1545 //TODO : homogeneiser les noms : SetPubElValByNumber
1546 // qui appelle PubElValSet.SetElValueByNumber
1547 // pourquoi pas SetPubElValueByNumber ??
1550 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1554 * \ingroup gdcmHeader
1555 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1556 * through tag name and modifies it's content with the given value.
1557 * @param content new value to substitute with
1558 * @param TagName name of the tag to be modified
1560 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1561 return ( PubElValSet.SetElValueByName (content, TagName) );
1565 * \ingroup gdcmHeader
1566 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1567 * through it's (group, element) and modifies it's length with
1569 * \warning Use with extreme caution.
1570 * @param length new length to substitute with
1571 * @param group group of the ElVal to modify
1572 * @param element element of the ElVal to modify
1573 * @return 1 on success, 0 otherwise.
1576 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1578 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1582 * \ingroup gdcmHeader
1583 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1584 * through it's (group, element) and modifies it's content with
1586 * @param content new value to substitute with
1587 * @param group group of the ElVal to modify
1588 * @param element element of the ElVal to modify
1589 * @return 1 on success, 0 otherwise.
1591 int gdcmHeader::SetShaElValByNumber(std::string content,
1592 guint16 group, guint16 element) {
1593 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1597 * \ingroup gdcmHeader
1598 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1599 * through tag name and modifies it's content with the given value.
1600 * @param content new value to substitute with
1601 * @param ShadowTagName name of the tag to be modified
1603 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1604 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1608 * \ingroup gdcmHeader
1609 * \brief Parses the header of the file but WITHOUT loading element values.
1611 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1612 gdcmElValue * newElValue = (gdcmElValue *)0;
1616 while ( (newElValue = ReadNextElement()) ) {
1617 SkipElementValue(newElValue);
1618 PubElValSet.Add(newElValue);
1623 * \ingroup gdcmHeader
1624 * \brief This predicate, based on hopefully reasonnable heuristics,
1625 * decides whether or not the current gdcmHeader was properly parsed
1626 * and contains the mandatory information for being considered as
1627 * a well formed and usable image.
1628 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1631 bool gdcmHeader::IsReadable(void) {
1632 if ( GetElValByName("Image Dimensions") != GDCM_UNFOUND
1633 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1636 if ( GetElValByName("Bits Allocated") == GDCM_UNFOUND )
1638 if ( GetElValByName("Bits Stored") == GDCM_UNFOUND )
1640 if ( GetElValByName("High Bit") == GDCM_UNFOUND )
1642 if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1648 * \ingroup gdcmHeader
1649 * \brief Small utility function that creates a new manually crafted
1650 * (as opposed as read from the file) gdcmElValue with user
1651 * specified name and adds it to the public tag hash table.
1652 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1653 * @param NewTagName The name to be given to this new tag.
1654 * @param VR The Value Representation to be given to this new tag.
1655 * @ return The newly hand crafted Element Value.
1657 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName,
1659 gdcmElValue* NewElVal = (gdcmElValue*)0;
1660 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1661 guint32 FreeElem = 0;
1662 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1664 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1665 if (FreeElem == UINT32_MAX) {
1666 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1667 "Group 0xffff in Public Dict is full");
1668 return (gdcmElValue*)0;
1670 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1671 VR, "GDCM", NewTagName);
1672 NewElVal = new gdcmElValue(NewEntry);
1673 PubElValSet.Add(NewElVal);
1678 * \ingroup gdcmHeader
1679 * \brief Loads the element values of all the elements present in the
1680 * public tag based hash table.
1682 void gdcmHeader::LoadElements(void) {
1684 TagElValueHT ht = PubElValSet.GetTagHt();
1685 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1686 LoadElementValue(tag->second);
1690 // Load 'non string' values
1691 std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);
1692 if( PhotometricInterpretation == "PALETTE COLOR " ){
1693 LoadElementVoidArea(0x0028,0x1200); // gray LUT
1694 LoadElementVoidArea(0x0028,0x1201); // R LUT
1695 LoadElementVoidArea(0x0028,0x1202); // G LUT
1696 LoadElementVoidArea(0x0028,0x1203); // B LUT
1698 LoadElementVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1699 LoadElementVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1700 LoadElementVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1703 // --------------------------------------------------------------
1704 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1706 // if recognition code tells us we deal with a LibIDO image
1707 // we switch lineNumber and columnNumber
1709 std::string RecCode;
1710 RecCode = GetPubElValByNumber(0x0008, 0x0010);
1711 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1712 RecCode == "CANRME_AILIBOD1_1." ) {
1713 filetype = ACR_LIBIDO;
1714 std::string rows = GetPubElValByNumber(0x0028, 0x0010);
1715 std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1716 SetPubElValByNumber(columns, 0x0028, 0x0010);
1717 SetPubElValByNumber(rows , 0x0028, 0x0011);
1719 // ----------------- End of Special Patch ----------------
1723 * \ingroup gdcmHeader
1727 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1728 PubElValSet.Print(os);
1732 * \ingroup gdcmHeader
1736 void gdcmHeader::PrintPubDict(std::ostream & os) {
1737 RefPubDict->Print(os);
1741 * \ingroup gdcmHeader
1745 int gdcmHeader::Write(FILE * fp, FileType type) {
1746 return PubElValSet.Write(fp, type);
1750 // ------------------------ 'non string' elements related functions
1754 * \ingroup gdcmHeader
1755 * \brief Loads (from disk) the element content
1756 * when a string is not suitable
1758 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1759 gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1762 size_t o =(size_t)Element->GetOffset();
1763 fseek(fp, o, SEEK_SET);
1764 int l=Element->GetLength();
1765 void * a = malloc(l);
1767 std::cout << "Big Broblem (LoadElementVoidArea, malloc) "
1768 << std::hex << Group << " " << Elem << std::endl;
1771 int res = PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1772 // TODO check the result
1773 size_t l2 = fread(a, 1, l ,fp);
1775 std::cout << "Big Broblem (LoadElementVoidArea, fread) "
1776 << std::hex << Group << " " << Elem << std::endl;
1783 * \ingroup gdcmHeader
1784 * \brief Gets (from Header) the offset of a 'non string' element value
1785 * \ (LoadElementValue has already be executed)
1788 * @return File Offset of the Element Value
1790 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1791 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1793 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1794 "failed to Locate gdcmElValue");
1797 return elValue->GetOffset();
1801 * \ingroup gdcmHeader
1802 * \brief Gets (from Header) a 'non string' element value
1803 * \ (LoadElementValue has already be executed)
1806 * @return Pointer to the 'non string' area
1809 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1810 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1812 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1813 "failed to Locate gdcmElValue");
1816 return elValue->GetVoidArea();
1821 // =============================================================================
1822 // Heuristics based accessors
1823 //==============================================================================
1826 // TODO : move to an other file.
1830 * \ingroup gdcmHeader
1831 * \brief Retrieve the number of columns of image.
1832 * @return The encountered size when found, 0 by default.
1834 int gdcmHeader::GetXSize(void) {
1835 // We cannot check for "Columns" because the "Columns" tag is present
1836 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1837 std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1838 if (StrSize == GDCM_UNFOUND)
1840 return atoi(StrSize.c_str());
1844 * \ingroup gdcmHeader
1845 * \brief Retrieve the number of lines of image.
1846 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1847 * @return The encountered size when found, 1 by default.
1849 int gdcmHeader::GetYSize(void) {
1850 // We cannot check for "Rows" because the "Rows" tag is present
1851 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1852 std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1853 if (StrSize != GDCM_UNFOUND)
1854 return atoi(StrSize.c_str());
1858 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1859 // hence be a signal (1d image). So we default to 1:
1864 * \ingroup gdcmHeader
1865 * \brief Retrieve the number of planes of volume or the number
1866 * of frames of a multiframe.
1867 * \warning When present we consider the "Number of Frames" as the third
1868 * dimension. When absent we consider the third dimension as
1869 * being the "Planes" tag content.
1870 * @return The encountered size when found, 1 by default.
1872 int gdcmHeader::GetZSize(void) {
1873 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1874 // as the third dimension.
1875 std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
1876 if (StrSize != GDCM_UNFOUND)
1877 return atoi(StrSize.c_str());
1879 // We then consider the "Planes" entry as the third dimension [we
1880 // cannot retrieve by name since "Planes tag is present both in
1881 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1882 StrSize = GetPubElValByNumber(0x0028,0x0012);
1883 if (StrSize != GDCM_UNFOUND)
1884 return atoi(StrSize.c_str());
1889 * \ingroup gdcmHeader
1890 * \brief Retrieve the number of Bits Stored
1891 * (as opposite to number of Bits Allocated)
1893 * @return The encountered number of Bits Stored, 0 by default.
1895 int gdcmHeader::GetBitsStored(void) {
1896 std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
1897 if (StrSize == GDCM_UNFOUND)
1899 return atoi(StrSize.c_str());
1904 * \ingroup gdcmHeader
1905 * \brief Retrieve the number of Samples Per Pixel
1906 * (1 : gray level, 3 : RGB)
1908 * @return The encountered number of Samples Per Pixel, 1 by default.
1910 int gdcmHeader::GetSamplesPerPixel(void) {
1911 std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
1912 if (StrSize == GDCM_UNFOUND)
1913 return 1; // Well, it's supposed to be mandatory ...
1914 return atoi(StrSize.c_str());
1918 * \ingroup gdcmHeader
1919 * \brief Retrieve the Planar Configuration for RGB images
1920 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1922 * @return The encountered Planar Configuration, 0 by default.
1924 int gdcmHeader::GetPlanarConfiguration(void) {
1925 std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
1926 if (StrSize == GDCM_UNFOUND)
1928 return atoi(StrSize.c_str());
1932 * \ingroup gdcmHeader
1933 * \brief Return the size (in bytes) of a single pixel of data.
1934 * @return The size in bytes of a single pixel of data.
1937 int gdcmHeader::GetPixelSize(void) {
1938 std::string PixelType = GetPixelType();
1939 if (PixelType == "8U" || PixelType == "8S")
1941 if (PixelType == "16U" || PixelType == "16S")
1943 if (PixelType == "32U" || PixelType == "32S")
1945 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1950 * \ingroup gdcmHeader
1951 * \brief Build the Pixel Type of the image.
1952 * Possible values are:
1953 * - 8U unsigned 8 bit,
1954 * - 8S signed 8 bit,
1955 * - 16U unsigned 16 bit,
1956 * - 16S signed 16 bit,
1957 * - 32U unsigned 32 bit,
1958 * - 32S signed 32 bit,
1959 * \warning 12 bit images appear as 16 bit.
1962 std::string gdcmHeader::GetPixelType(void) {
1963 std::string BitsAlloc;
1964 BitsAlloc = GetElValByName("Bits Allocated");
1965 if (BitsAlloc == GDCM_UNFOUND) {
1966 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1967 BitsAlloc = std::string("16");
1969 if (BitsAlloc == "12")
1970 BitsAlloc = std::string("16");
1973 Signed = GetElValByName("Pixel Representation");
1974 if (Signed == GDCM_UNFOUND) {
1975 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1976 BitsAlloc = std::string("0");
1979 Signed = std::string("U");
1981 Signed = std::string("S");
1983 return( BitsAlloc + Signed);
1987 * \ingroup gdcmHeader
1988 * \brief gets the info from 0002,0010 : Transfert Syntax
1990 * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
1992 std::string gdcmHeader::GetTransferSyntaxName(void) {
1993 std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
1994 if (TransfertSyntax == GDCM_UNFOUND) {
1995 dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
1996 return "Uncompressed ACR-NEMA";
1998 // we do it only when we need it
1999 gdcmTS * ts = gdcmGlobal::GetTS();
2000 std::string tsName=ts->GetValue(TransfertSyntax);
2001 //delete ts; // Seg Fault when deleted ?!
2005 // -------------------------------- Lookup Table related functions ------------
2008 * \ingroup gdcmHeader
2009 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2011 * @return Lookup Table Length
2012 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2015 int gdcmHeader::GetLUTLength(void) {
2016 std::vector<std::string> tokens;
2020 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2021 std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2022 if (LutDescriptionR == GDCM_UNFOUND)
2024 std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2025 if (LutDescriptionG == GDCM_UNFOUND)
2027 std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2028 if (LutDescriptionB == GDCM_UNFOUND)
2030 if( (LutDescriptionR != LutDescriptionG) || (LutDescriptionR != LutDescriptionB) ) {
2031 dbg.Verbose(0, "gdcmHeader::GetLUTLength: The CLUT R,G,B are not equal");
2034 std::cout << "Lut Description " << LutDescriptionR <<std::endl;
2035 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2036 Tokenize (LutDescriptionR, tokens, "\\");
2037 LutLength=atoi(tokens[0].c_str());
2038 //LutDepth=atoi(tokens[1].c_str());
2039 //LutNbits=atoi(tokens[2].c_str());
2045 * \ingroup gdcmHeader
2046 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2048 * @return Lookup Table nBit
2049 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2052 int gdcmHeader::GetLUTNbits(void) {
2053 std::vector<std::string> tokens;
2057 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2058 // Consistency already checked in GetLUTLength
2059 std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2060 if (LutDescription == GDCM_UNFOUND)
2062 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2063 Tokenize (LutDescription, tokens, "\\");
2064 //LutLength=atoi(tokens[0].c_str());
2065 //LutDepth=atoi(tokens[1].c_str());
2066 LutNbits=atoi(tokens[2].c_str());
2073 * \ingroup gdcmHeader
2074 * \brief gets the info from 0028,1201 : Lookup Table Red
2076 * @return Lookup Table Red
2077 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2079 void * gdcmHeader::GetLUTRed(void) {
2080 return GetPubElValVoidAreaByNumber(0x0028,0x1201);
2084 * \ingroup gdcmHeader
2085 * \brief gets the info from 0028,1202 : Lookup Table Green
2087 * @return Lookup Table Red
2088 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2090 void * gdcmHeader::GetLUTGreen(void) {
2091 return GetPubElValVoidAreaByNumber(0x0028,0x1202);
2095 * \ingroup gdcmHeader
2096 * \brief gets the info from 0028,1202 : Lookup Table Blue
2098 * @return Lookup Table Blue
2099 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2101 void * gdcmHeader::GetLUTBlue(void) {
2102 return GetPubElValVoidAreaByNumber(0x0028,0x1203);
2106 * \ingroup gdcmHeader
2108 * @return Lookup Table RGB
2109 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2110 * \ and (0028,1201),(0028,1202),(0028,1202) are found
2111 * \warning : hazardous ! Use better GetPubElValVoidAreaByNumber
2113 void * gdcmHeader::GetLUTRGB(void) {
2114 // Not so easy : see
2115 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2116 // and OT-PAL-8-face.dcm
2118 if (GetPubElValByNumber(0x0028,0x0004) == GDCM_UNFOUND) {
2119 dbg.Verbose(0, "gdcmHeader::GetLUTRGB: unfound Photometric Interpretation");
2122 void * LutR,*LutG,*LutB;
2125 // Maybe, some day we get an image
2126 // that respects the definition ...
2127 // Let's consider no ones does.
2132 int nBits=GetLUTNbits();
2134 // a virer quand on aura trouve UNE image
2135 // qui correspond VRAIMENT à la definition !
2136 std::cout << "l " << l << " nBits " << nBits;
2140 LutR =GetPubElValVoidAreaByNumber(0x0028,0x1201);
2141 LutG =GetPubElValVoidAreaByNumber(0x0028,0x1202);
2142 LutB =GetPubElValVoidAreaByNumber(0x0028,0x1203);
2144 // Warning : Any value for nBits as to be considered as 8
2145 // Any value for Length as to be considered as 256
2148 // Just wait before removing the following code
2151 guint16 * LUTRGB, *rgb;
2152 LUTRGB = rgb = (guint16 *) malloc(3*l*sizeof( guint16));
2153 guint16 * r = (guint16 *)LutR;
2154 guint16 * g = (guint16 *)LutG;
2155 guint16 * b = (guint16 *)LutB;
2156 for(int i=0;i<l;i++) {
2164 */ { // we assume it's always 8 Bits
2165 l=256; // we assume ...
2166 unsigned char * LUTRGB, *rgb;
2167 LUTRGB = rgb = (unsigned char *) malloc(3*l*sizeof( char));
2168 unsigned char * r = (unsigned char *)LutR;
2169 unsigned char * g = (unsigned char *)LutG;
2170 unsigned char * b = (unsigned char *)LutB;
2171 for(int i=0;i<l;i++) {
2172 //std::cout << "lut16 " << i << " : " << *r << " " << *g << " " << *b
2174 printf("lut 8 %d : %d %d %d \n",i,*r,*g,*b);
2179 free(LutR); free(LutB); free(LutG);
2183 /* Sorry for the comments. The code will be moved in a fonction
2185 std::string x=GetPubElValByNumber(0x0028,0x1201);
2186 unsigned short int * lutR = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2187 unsigned short int * lutG = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2188 unsigned short int * lutB = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2190 std::vector<std::string> tokens;
2191 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2192 Tokenize ((const std::string)x, tokens, "\\");
2193 for (unsigned int i=0; i<tokens.size();i++) {
2194 lutR[i] = atoi(tokens[i].c_str());
2195 printf("%d (%x)\n",lutR[i],lutR[i]);
2198 std::string y=GetPubElValByNumber(0x0028,0x1202);
2199 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2200 Tokenize ((const std::string)y, tokens, "\\");
2201 for (unsigned int i=0; i<tokens.size();i++) {
2202 lutG[i] = atoi(tokens[i].c_str());
2205 std::string z=GetPubElValByNumber(0x0028,0x1203);
2206 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2207 Tokenize ((const std::string)z, tokens, "\\");
2208 for (unsigned int i=0; i<tokens.size();i++) {
2209 lutB[i] = atoi(tokens[i].c_str());
2211 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2212 Tokenize ((const std::string)x, tokens, "\\");
2213 for (unsigned int i=0; i<tokens.size();i++) {
2214 lutB[i] = atoi(tokens[i].c_str());
2219 //int lgth=GetLUTLength();
2220 //cout << "lgth " << lgth << std::endl;;
2221 //for (int j=0;j<lgth;j++){
2222 //printf ("%d : %d (%x) %d (%x) %d (%x)\n",j,lutR[j],lutR[j],lutG[j],lutG[j],lutB[j],lutB[j]);