1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.89 2003/09/24 13:52:46 jpr Exp $
3 //This is needed when compiling in debug mode
5 //'identifier' : not all control paths return a value
6 //#pragma warning ( disable : 4715 )
7 // 'identifier' : class 'type' needs to have dll-interface to be used by
8 // clients of class 'type2'
9 #pragma warning ( disable : 4251 )
10 // 'identifier' : identifier was truncated to 'number' characters in the
12 #pragma warning ( disable : 4786 )
21 #include <netinet/in.h>
23 #include <cctype> // for isalpha
26 #include "gdcmHeader.h"
29 // Refer to gdcmHeader::CheckSwap()
30 #define HEADER_LENGTH_TO_READ 256
31 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
32 //#define _MaxSizeLoadElementValue_ 1024
33 #define _MaxSizeLoadElementValue_ 4096
38 void gdcmHeader::Initialise(void) {
39 dicom_vr = gdcmGlobal::GetVR();
40 dicom_ts = gdcmGlobal::GetTS();
41 Dicts = gdcmGlobal::GetDicts();
42 RefPubDict = Dicts->GetDefaultPubDict();
43 RefShaDict = (gdcmDict*)0;
50 * @param exception_on_error
52 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) {
53 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
54 filename = InFilename;
56 if ( !OpenFile(exception_on_error))
66 * @param exception_on_error
68 gdcmHeader::gdcmHeader(bool exception_on_error) {
69 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
76 * @param exception_on_error
79 bool gdcmHeader::OpenFile(bool exception_on_error)
80 throw(gdcmFileError) {
81 fp=fopen(filename.c_str(),"rb");
82 if(exception_on_error) {
84 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
88 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
95 * @return TRUE if the close was successfull
97 bool gdcmHeader::CloseFile(void) {
98 int closed = fclose(fp);
106 * \ingroup gdcmHeader
107 * \brief Canonical destructor.
109 gdcmHeader::~gdcmHeader (void) {
110 dicom_vr = (gdcmVR*)0;
111 Dicts = (gdcmDictSet*)0;
112 RefPubDict = (gdcmDict*)0;
113 RefShaDict = (gdcmDict*)0;
119 // META Meta Information
131 // NMI Nuclear Medicine
133 // BFS Basic Film Session
134 // BFB Basic Film Box
135 // BIB Basic Image Box
151 * \ingroup gdcmHeader
152 * \brief Discover what the swap code is (among little endian, big endian,
153 * bad little endian, bad big endian).
156 void gdcmHeader::CheckSwap()
158 // The only guaranted way of finding the swap code is to find a
159 // group tag since we know it's length has to be of four bytes i.e.
160 // 0x00000004. Finding the swap code in then straigthforward. Trouble
161 // occurs when we can't find such group...
163 guint32 x=4; // x : for ntohs
164 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
168 char deb[HEADER_LENGTH_TO_READ];
170 // First, compare HostByteOrder and NetworkByteOrder in order to
171 // determine if we shall need to swap bytes (i.e. the Endian type).
177 // The easiest case is the one of a DICOM header, since it possesses a
178 // file preamble where it suffice to look for the string "DICM".
179 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
182 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
183 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
184 // Next, determine the value representation (VR). Let's skip to the
185 // first element (0002, 0000) and check there if we find "UL"
186 // - or "OB" if the 1st one is (0002,0001) -,
187 // in which case we (almost) know it is explicit VR.
188 // WARNING: if it happens to be implicit VR then what we will read
189 // is the length of the group. If this ascii representation of this
190 // length happens to be "UL" then we shall believe it is explicit VR.
191 // FIXME: in order to fix the above warning, we could read the next
192 // element value (or a couple of elements values) in order to make
193 // sure we are not commiting a big mistake.
195 // * the 128 bytes of File Preamble (often padded with zeroes),
196 // * the 4 bytes of "DICM" string,
197 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
198 // i.e. a total of 136 bytes.
201 // Use gdcmHeader::dicom_vr to test all the possibilities
202 // instead of just checking for UL, OB and UI !?
203 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
204 (memcmp(entCur, "OB", (size_t)2) == 0) ||
205 (memcmp(entCur, "UI", (size_t)2) == 0) )
207 filetype = ExplicitVR;
208 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
209 "explicit Value Representation");
211 filetype = ImplicitVR;
212 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
213 "not an explicit Value Representation");
217 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
218 "HostByteOrder != NetworkByteOrder");
221 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
222 "HostByteOrder = NetworkByteOrder");
225 // Position the file position indicator at first tag (i.e.
226 // after the file preamble and the "DICM" string).
228 fseek (fp, 132L, SEEK_SET);
232 // Alas, this is not a DicomV3 file and whatever happens there is no file
233 // preamble. We can reset the file position indicator to where the data
234 // is (i.e. the beginning of the file).
235 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
238 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
239 // By clean we mean that the length of the first tag is written down.
240 // If this is the case and since the length of the first group HAS to be
241 // four (bytes), then determining the proper swap code is straightforward.
244 // We assume the array of char we are considering contains the binary
245 // representation of a 32 bits integer. Hence the following dirty
247 s = *((guint32 *)(entCur));
267 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
268 "ACR/NEMA unfound swap info (time to raise bets)");
271 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
272 // It is time for despaired wild guesses. So, let's assume this file
273 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
274 // not present. Then the only info we have is the net2host one.
284 * \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.
311 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
312 if (filetype != ExplicitVR)
318 char msg[100]; // for sprintf. Sorry
320 long PositionOnEntry = ftell(fp);
321 // Warning: we believe this is explicit VR (Value Representation) because
322 // we used a heuristic that found "UL" in the first tag. Alas this
323 // doesn't guarantee that all the tags will be in explicit VR. In some
324 // cases (see e-film filtered files) one finds implicit VR tags mixed
325 // within an explicit VR file. Hence we make sure the present tag
326 // is in explicit VR and try to fix things if it happens not to be
328 bool RealExplicit = true;
330 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
332 vr = std::string(VR);
334 // Assume we are reading a falsely explicit VR file i.e. we reached
335 // a tag where we expect reading a VR but are in fact we read the
336 // first to bytes of the length. Then we will interogate (through find)
337 // the dicom_vr dictionary with oddities like "\004\0" which crashes
338 // both GCC and VC++ implementations of the STL map. Hence when the
339 // expected VR read happens to be non-ascii characters we consider
340 // we hit falsely explicit VR tag.
342 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
343 RealExplicit = false;
345 // CLEANME searching the dicom_vr at each occurence is expensive.
346 // PostPone this test in an optional integrity check at the end
347 // of parsing or only in debug mode.
348 if ( RealExplicit && !dicom_vr->Count(vr) )
351 if ( RealExplicit ) {
352 if ( ElVal->IsVrUnknown() ) {
353 // When not a dictionary entry, we can safely overwrite the vr.
357 if ( ElVal->GetVR() == vr ) {
358 // The vr we just read and the dictionary agree. Nothing to do.
361 // The vr present in the file and the dictionary disagree. We assume
362 // the file writer knew best and use the vr of the file. Since it would
363 // be unwise to overwrite the vr of a dictionary (since it would
364 // compromise it's next user), we need to clone the actual DictEntry
365 // and change the vr for the read one.
366 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
371 ElVal->SetDictEntry(NewTag);
375 // We thought this was explicit VR, but we end up with an
376 // implicit VR tag. Let's backtrack.
378 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", ElVal->GetGroup(),ElVal->GetElement());
379 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
381 fseek(fp, PositionOnEntry, SEEK_SET);
382 // When this element is known in the dictionary we shall use, e.g. for
383 // the semantics (see the usage of IsAnInteger), the vr proposed by the
384 // dictionary entry. Still we have to flag the element as implicit since
385 // we know now our assumption on expliciteness is not furfilled.
387 if ( ElVal->IsVrUnknown() )
388 ElVal->SetVR("Implicit");
389 ElVal->SetImplicitVr();
393 * \ingroup gdcmHeader
394 * \brief Determines if the Transfer Syntax was already encountered
395 * and if it corresponds to a ImplicitVRLittleEndian one.
397 * @return True when ImplicitVRLittleEndian found. False in all other cases.
399 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
400 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
403 LoadElementValueSafe(Element);
404 std::string Transfer = Element->GetValue();
405 if ( Transfer == "1.2.840.10008.1.2" )
411 * \ingroup gdcmHeader
412 * \brief Determines if the Transfer Syntax was already encountered
413 * and if it corresponds to a ExplicitVRLittleEndian one.
415 * @return True when ExplicitVRLittleEndian found. False in all other cases.
417 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
418 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
421 LoadElementValueSafe(Element);
422 std::string Transfer = Element->GetValue();
423 if ( Transfer == "1.2.840.10008.1.2.1" )
429 * \ingroup gdcmHeader
430 * \brief Determines if the Transfer Syntax was already encountered
431 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
433 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
435 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
436 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
439 LoadElementValueSafe(Element);
440 std::string Transfer = Element->GetValue();
441 if ( Transfer == "1.2.840.10008.1.2.1.99" )
447 * \ingroup gdcmHeader
448 * \brief Determines if the Transfer Syntax was already encountered
449 * and if it corresponds to a Explicit VR Big Endian one.
451 * @return True when big endian found. False in all other cases.
453 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
454 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
457 LoadElementValueSafe(Element);
458 std::string Transfer = Element->GetValue();
459 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
465 * \ingroup gdcmHeader
466 * \brief Determines if the Transfer Syntax was already encountered
467 * and if it corresponds to a JPEGBaseLineProcess1 one.
469 * @return True when JPEGBaseLineProcess1found. False in all other cases.
471 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
472 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
475 LoadElementValueSafe(Element);
476 std::string Transfer = Element->GetValue();
477 if ( Transfer == "1.2.840.10008.1.2.4.50" )
483 * \ingroup gdcmHeader
488 bool gdcmHeader::IsJPEGLossless(void) {
489 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
490 // faire qq chose d'intelligent a la place de ça
493 LoadElementValueSafe(Element);
494 const char * Transfert = Element->GetValue().c_str();
495 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
496 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
502 * \ingroup gdcmHeader
503 * \brief Determines if the Transfer Syntax was already encountered
504 * and if it corresponds to a JPEGExtendedProcess2-4 one.
506 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
508 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
509 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
512 LoadElementValueSafe(Element);
513 std::string Transfer = Element->GetValue();
514 if ( Transfer == "1.2.840.10008.1.2.4.51" )
520 * \ingroup gdcmHeader
521 * \brief Determines if the Transfer Syntax was already encountered
522 * and if it corresponds to a JPEGExtendeProcess3-5 one.
524 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
526 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
527 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
530 LoadElementValueSafe(Element);
531 std::string Transfer = Element->GetValue();
532 if ( Transfer == "1.2.840.10008.1.2.4.52" )
538 * \ingroup gdcmHeader
539 * \brief Determines if the Transfer Syntax was already encountered
540 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
542 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
545 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
546 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
549 LoadElementValueSafe(Element);
550 std::string Transfer = Element->GetValue();
551 if ( Transfer == "1.2.840.10008.1.2.4.53" )
557 * \ingroup gdcmHeader
558 * \brief Determines if the Transfer Syntax was already encountered
559 * and if it corresponds to a RLE Lossless one.
561 * @return True when RLE Lossless found. False in all
564 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
565 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
568 LoadElementValueSafe(Element);
569 std::string Transfer = Element->GetValue();
570 if ( Transfer == "1.2.840.10008.1.2.5" )
576 * \ingroup gdcmHeader
577 * \brief Determines if the Transfer Syntax was already encountered
578 * and if it corresponds to a JPEG200 one.0
580 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
583 bool gdcmHeader::IsJPEG2000(void) {
584 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
587 LoadElementValueSafe(Element);
588 std::string Transfer = Element->GetValue();
589 if ( (Transfer == "1.2.840.10008.1.2.4.90")
590 || (Transfer == "1.2.840.10008.1.2.4.91") )
596 * \ingroup gdcmHeader
597 * \brief Predicate for dicom version 3 file.
598 * @return True when the file is a dicom version 3.
600 bool gdcmHeader::IsDicomV3(void) {
601 if ( (filetype == ExplicitVR)
602 || (filetype == ImplicitVR) )
608 * \ingroup gdcmHeader
609 * \brief When the length of an element value is obviously wrong (because
610 * the parser went Jabberwocky) one can hope improving things by
611 * applying this heuristic.
613 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
614 if ( FoundLength == 0xffffffff)
616 ElVal->SetLength(FoundLength);
620 * \ingroup gdcmHeader
625 guint32 gdcmHeader::FindLengthOB(void) {
626 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
629 long PositionOnEntry = ftell(fp);
630 bool FoundSequenceDelimiter = false;
631 guint32 TotalLength = 0;
634 while ( ! FoundSequenceDelimiter) {
642 TotalLength += 4; // We even have to decount the group and element
644 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
645 char msg[100]; // for sprintf. Sorry
646 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
647 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
652 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
653 FoundSequenceDelimiter = true;
654 else if ( n != 0xe000 ){
655 char msg[100]; // for sprintf. Sorry
656 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,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 "on est sur 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, guint16 Group, guint16 Elem ) {
1088 // TODO : FIXME JPRx
1090 // on (je) cree une Elvalue ne contenant pas de valeur
1091 // on l'ajoute au ElValSet
1092 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1093 // --> devrait pouvoir etre fait + simplement ???
1095 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1096 PubElValSet.Add(nvElValue);
1097 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1103 * \ingroup gdcmHeader
1104 * \brief Modify or (Creates if not found) an element
1105 * @param Value new value
1108 * \return integer acts as a boolean
1111 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1113 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1114 PubElValSet.Add(nvElValue);
1115 std::string v = Value;
1116 PubElValSet.SetElValueByNumber(v, Group, Elem);
1122 * \ingroup gdcmHeader
1123 * \brief Set a new value if the invoked element exists
1127 * \return integer acts as a boolean
1129 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1131 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1132 std::string v = Value;
1133 PubElValSet.SetElValueByNumber(v, Group, Elem);
1139 * \ingroup gdcmHeader
1140 * \brief Checks if a given ElValue (group,number)
1141 * \ exists in the Public ElValSet
1144 * @return integer acts as a boolean
1147 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1148 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1152 * \ingroup gdcmHeader
1153 * \brief Build a new Element Value from all the low level arguments.
1154 * Check for existence of dictionary entry, and build
1155 * a default one when absent.
1156 * @param Name Name of the underlying DictEntry
1158 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1160 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1162 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1164 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1166 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1167 "failed to allocate gdcmElValue");
1168 return (gdcmElValue*)0;
1174 * \ingroup gdcmHeader
1175 * \brief Read the next tag but WITHOUT loading it's value
1176 * @return On succes the newly created ElValue, NULL on failure.
1178 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1181 gdcmElValue * NewElVal;
1186 if ( (g==0x7fe0) && (n==0x0010) )
1189 // We reached the EOF (or an error occured) and header parsing
1190 // has to be considered as finished.
1191 return (gdcmElValue *)0;
1193 NewElVal = NewElValueByNumber(g, n);
1195 FindLength(NewElVal);
1198 return (gdcmElValue *)0;
1200 NewElVal->SetOffset(ftell(fp));
1201 if ( (g==0x7fe0) && (n==0x0010) )
1206 * \ingroup gdcmHeader
1207 * \brief Apply some heuristics to predict wether the considered
1208 * element value contains/represents an integer or not.
1209 * @param ElVal The element value on which to apply the predicate.
1210 * @return The result of the heuristical predicate.
1212 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1213 guint16 group = ElVal->GetGroup();
1214 guint16 element = ElVal->GetElement();
1215 std::string vr = ElVal->GetVR();
1216 guint32 length = ElVal->GetLength();
1218 // When we have some semantics on the element we just read, and if we
1219 // a priori know we are dealing with an integer, then we shall be
1220 // able to swap it's element value properly.
1221 if ( element == 0 ) { // This is the group length of the group
1225 dbg.Error("gdcmHeader::IsAnInteger",
1226 "Erroneous Group Length element length.");
1229 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1236 * \ingroup gdcmHeader
1237 * \brief Recover the offset (from the beginning of the file) of the pixels.
1239 size_t gdcmHeader::GetPixelOffset(void) {
1240 // If this file complies with the norm we should encounter the
1241 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1242 // the group that contains the pixel data (hence the "Pixel Data"
1243 // is found by indirection through the "Image Location").
1244 // Inside the group pointed by "Image Location" the searched element
1245 // is conventionally the element 0x0010 (when the norm is respected).
1246 // When the "Image Location" is absent we default to group 0x7fe0.
1249 std::string ImageLocation = GetPubElValByName("Image Location");
1250 if ( ImageLocation == GDCM_UNFOUND ) {
1253 grPixel = (guint16) atoi( ImageLocation.c_str() );
1255 if (grPixel != 0x7fe0)
1256 // This is a kludge for old dirty Philips imager.
1261 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1264 return PixelElement->GetOffset();
1270 * \ingroup gdcmHeader
1271 * \brief Searches both the public and the shadow dictionary (when they
1272 * exist) for the presence of the DictEntry with given
1273 * group and element. The public dictionary has precedence on the
1275 * @param group group of the searched DictEntry
1276 * @param element element of the searched DictEntry
1277 * @return Corresponding DictEntry when it exists, NULL otherwise.
1279 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1281 gdcmDictEntry * found = (gdcmDictEntry*)0;
1282 if (!RefPubDict && !RefShaDict) {
1283 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1284 "we SHOULD have a default dictionary");
1287 found = RefPubDict->GetTagByNumber(group, element);
1292 found = RefShaDict->GetTagByNumber(group, element);
1300 * \ingroup gdcmHeader
1301 * \brief Searches both the public and the shadow dictionary (when they
1302 * exist) for the presence of the DictEntry with given name.
1303 * The public dictionary has precedence on the shadow one.
1304 * @param Name name of the searched DictEntry
1305 * @return Corresponding DictEntry when it exists, NULL otherwise.
1307 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1308 gdcmDictEntry * found = (gdcmDictEntry*)0;
1309 if (!RefPubDict && !RefShaDict) {
1310 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1311 "we SHOULD have a default dictionary");
1314 found = RefPubDict->GetTagByName(Name);
1319 found = RefShaDict->GetTagByName(Name);
1327 * \ingroup gdcmHeader
1328 * \brief Searches within the public dictionary for element value of
1330 * @param group Group of the researched tag.
1331 * @param element Element of the researched tag.
1332 * @return Corresponding element value when it exists, and the string
1333 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1335 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1336 return PubElValSet.GetElValueByNumber(group, element);
1340 * \ingroup gdcmHeader
1341 * \brief Searches within the public dictionary for element value
1342 * representation of a given tag.
1344 * Obtaining the VR (Value Representation) might be needed by caller
1345 * to convert the string typed content to caller's native type
1346 * (think of C++ vs Python). The VR is actually of a higher level
1347 * of semantics than just the native C++ type.
1348 * @param group Group of the researched tag.
1349 * @param element Element of the researched tag.
1350 * @return Corresponding element value representation when it exists,
1351 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1353 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1354 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1356 return GDCM_UNFOUND;
1357 return elem->GetVR();
1361 * \ingroup gdcmHeader
1362 * \brief Searches within the public dictionary for element value of
1364 * @param TagName name of the researched element.
1365 * @return Corresponding element value when it exists, and the string
1366 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1368 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1369 return PubElValSet.GetElValueByName(TagName);
1373 * \ingroup gdcmHeader
1374 * \brief Searches within the elements parsed with the public dictionary for
1375 * the element value representation of a given tag.
1377 * Obtaining the VR (Value Representation) might be needed by caller
1378 * to convert the string typed content to caller's native type
1379 * (think of C++ vs Python). The VR is actually of a higher level
1380 * of semantics than just the native C++ type.
1381 * @param TagName name of the researched element.
1382 * @return Corresponding element value representation when it exists,
1383 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1385 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1386 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1388 return GDCM_UNFOUND;
1389 return elem->GetVR();
1393 * \ingroup gdcmHeader
1394 * \brief Searches within elements parsed with the SHADOW dictionary
1395 * for the element value of a given tag.
1396 * @param group Group of the researched tag.
1397 * @param element Element of the researched tag.
1398 * @return Corresponding element value representation when it exists,
1399 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1401 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1402 return ShaElValSet.GetElValueByNumber(group, element);
1406 * \ingroup gdcmHeader
1407 * \brief Searches within the elements parsed with the SHADOW dictionary
1408 * for the element value representation of a given tag.
1410 * Obtaining the VR (Value Representation) might be needed by caller
1411 * to convert the string typed content to caller's native type
1412 * (think of C++ vs Python). The VR is actually of a higher level
1413 * of semantics than just the native C++ type.
1414 * @param group Group of the researched tag.
1415 * @param element Element of the researched tag.
1416 * @return Corresponding element value representation when it exists,
1417 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1419 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1420 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1422 return GDCM_UNFOUND;
1423 return elem->GetVR();
1427 * \ingroup gdcmHeader
1428 * \brief Searches within the elements parsed with the shadow dictionary
1429 * for an element value of given tag.
1430 * @param TagName name of the researched element.
1431 * @return Corresponding element value when it exists, and the string
1432 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1434 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1435 return ShaElValSet.GetElValueByName(TagName);
1439 * \ingroup gdcmHeader
1440 * \brief Searches within the elements parsed with the shadow dictionary for
1441 * 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 ("gdcm::Unfound") otherwise.
1451 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1452 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1454 return GDCM_UNFOUND;
1455 return elem->GetVR();
1459 * \ingroup gdcmHeader
1460 * \brief Searches within elements parsed with the public dictionary
1461 * and then within the elements parsed with the shadow dictionary
1462 * for the element value of a given tag.
1463 * @param group Group of the researched tag.
1464 * @param element Element of the researched tag.
1465 * @return Corresponding element value representation when it exists,
1466 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1468 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1469 std::string pub = GetPubElValByNumber(group, element);
1472 return GetShaElValByNumber(group, element);
1476 * \ingroup gdcmHeader
1477 * \brief Searches within elements parsed with the public dictionary
1478 * and then within the elements parsed with the shadow dictionary
1479 * for the element value representation of a given tag.
1481 * Obtaining the VR (Value Representation) might be needed by caller
1482 * to convert the string typed content to caller's native type
1483 * (think of C++ vs Python). The VR is actually of a higher level
1484 * of semantics than just the native C++ type.
1485 * @param group Group of the researched tag.
1486 * @param element Element of the researched tag.
1487 * @return Corresponding element value representation when it exists,
1488 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1490 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1491 std::string pub = GetPubElValRepByNumber(group, element);
1494 return GetShaElValRepByNumber(group, element);
1498 * \ingroup gdcmHeader
1499 * \brief Searches within elements parsed with the public dictionary
1500 * and then within the elements parsed with the shadow dictionary
1501 * for the element value of a given tag.
1502 * @param TagName name of the researched element.
1503 * @return Corresponding element value when it exists,
1504 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1506 std::string gdcmHeader::GetElValByName(std::string TagName) {
1507 std::string pub = GetPubElValByName(TagName);
1510 return GetShaElValByName(TagName);
1514 * \ingroup gdcmHeader
1515 * \brief Searches within elements parsed with the public dictionary
1516 * and then within the elements parsed with the shadow dictionary
1517 * for the element value representation of a given tag.
1519 * Obtaining the VR (Value Representation) might be needed by caller
1520 * to convert the string typed content to caller's native type
1521 * (think of C++ vs Python). The VR is actually of a higher level
1522 * of semantics than just the native C++ type.
1523 * @param TagName name of the researched element.
1524 * @return Corresponding element value representation when it exists,
1525 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1527 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1528 std::string pub = GetPubElValRepByName(TagName);
1531 return GetShaElValRepByName(TagName);
1535 * \ingroup gdcmHeader
1536 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1537 * through it's (group, element) and modifies it's content with
1539 * @param content new value to substitute with
1540 * @param group group of the ElVal to modify
1541 * @param element element of the ElVal to modify
1543 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1546 //TODO : homogeneiser les noms : SetPubElValByNumber 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, std::string VR) {
1658 gdcmElValue* NewElVal = (gdcmElValue*)0;
1659 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1660 guint32 FreeElem = 0;
1661 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1663 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1664 if (FreeElem == UINT32_MAX) {
1665 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1666 "Group 0xffff in Public Dict is full");
1667 return (gdcmElValue*)0;
1669 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1670 VR, "GDCM", NewTagName);
1671 NewElVal = new gdcmElValue(NewEntry);
1672 PubElValSet.Add(NewElVal);
1677 * \ingroup gdcmHeader
1678 * \brief Loads the element values of all the elements present in the
1679 * public tag based hash table.
1681 void gdcmHeader::LoadElements(void) {
1683 TagElValueHT ht = PubElValSet.GetTagHt();
1684 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1685 LoadElementValue(tag->second);
1689 // Load 'non string' values
1690 std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);
1691 if( PhotometricInterpretation == "PALETTE COLOR " ){
1692 LoadElementVoidArea(0x0028,0x1200); // gray LUT
1693 LoadElementVoidArea(0x0028,0x1201); // R LUT
1694 LoadElementVoidArea(0x0028,0x1202); // G LUT
1695 LoadElementVoidArea(0x0028,0x1203); // B LUT
1697 LoadElementVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1698 LoadElementVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1699 LoadElementVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1702 // --------------------------------------------------------------
1703 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1705 // if recognition code tells us we deal with a LibIDO image
1706 // we switch lineNumber and columnNumber
1708 std::string RecCode;
1709 RecCode = GetPubElValByNumber(0x0008, 0x0010);
1710 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1711 RecCode == "CANRME_AILIBOD1_1." ) {
1712 filetype = ACR_LIBIDO;
1713 std::string rows = GetPubElValByNumber(0x0028, 0x0010);
1714 std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1715 SetPubElValByNumber(columns, 0x0028, 0x0010);
1716 SetPubElValByNumber(rows , 0x0028, 0x0011);
1718 // ----------------- End of Special Patch ----------------
1722 * \ingroup gdcmHeader
1726 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1727 PubElValSet.Print(os);
1731 * \ingroup gdcmHeader
1735 void gdcmHeader::PrintPubDict(std::ostream & os) {
1736 RefPubDict->Print(os);
1740 * \ingroup gdcmHeader
1744 int gdcmHeader::Write(FILE * fp, FileType type) {
1745 return PubElValSet.Write(fp, type);
1749 // ------------------------ 'non string' elements related functions
1753 * \ingroup gdcmHeader
1754 * \brief Loads (from disk) the element content
1755 * when a string is not suitable
1757 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1758 gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1761 size_t o =(size_t)Element->GetOffset();
1762 fseek(fp, o, SEEK_SET);
1763 int l=Element->GetLength();
1764 void * a = malloc(l);
1766 std::cout << "Big Broblem (LoadElementVoidArea, malloc) "
1767 << std::hex << Group << " " << Elem << std::endl;
1770 int res = PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1771 // TODO check the result
1772 size_t l2 = fread(a, 1, l ,fp);
1774 std::cout << "Big Broblem (LoadElementVoidArea, fread) "
1775 << std::hex << Group << " " << Elem << std::endl;
1782 * \ingroup gdcmHeader
1783 * \brief Gets (from Header) the offset of a 'non string' element value
1784 * \ (LoadElementValue has already be executed)
1787 * @return File Offset of the Element Value
1789 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1790 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1792 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1793 "failed to Locate gdcmElValue");
1796 return elValue->GetOffset();
1800 * \ingroup gdcmHeader
1801 * \brief Gets (from Header) a 'non string' element value
1802 * \ (LoadElementValue has already be executed)
1805 * @return Pointer to the 'non string' area
1808 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1809 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1811 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1812 "failed to Locate gdcmElValue");
1815 return elValue->GetVoidArea();
1820 // =============================================================================
1821 // Heuristics based accessors
1822 //==============================================================================
1825 // TODO : move to an other file.
1829 * \ingroup gdcmHeader
1830 * \brief Retrieve the number of columns of image.
1831 * @return The encountered size when found, 0 by default.
1833 int gdcmHeader::GetXSize(void) {
1834 // We cannot check for "Columns" because the "Columns" tag is present
1835 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1836 std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1837 if (StrSize == GDCM_UNFOUND)
1839 return atoi(StrSize.c_str());
1843 * \ingroup gdcmHeader
1844 * \brief Retrieve the number of lines of image.
1845 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1846 * @return The encountered size when found, 1 by default.
1848 int gdcmHeader::GetYSize(void) {
1849 // We cannot check for "Rows" because the "Rows" tag is present
1850 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1851 std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1852 if (StrSize != GDCM_UNFOUND)
1853 return atoi(StrSize.c_str());
1857 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1858 // hence be a signal (1d image). So we default to 1:
1863 * \ingroup gdcmHeader
1864 * \brief Retrieve the number of planes of volume or the number
1865 * of frames of a multiframe.
1866 * \warning When present we consider the "Number of Frames" as the third
1867 * dimension. When absent we consider the third dimension as
1868 * being the "Planes" tag content.
1869 * @return The encountered size when found, 1 by default.
1871 int gdcmHeader::GetZSize(void) {
1872 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1873 // as the third dimension.
1874 std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
1875 if (StrSize != GDCM_UNFOUND)
1876 return atoi(StrSize.c_str());
1878 // We then consider the "Planes" entry as the third dimension [we
1879 // cannot retrieve by name since "Planes tag is present both in
1880 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1881 StrSize = GetPubElValByNumber(0x0028,0x0012);
1882 if (StrSize != GDCM_UNFOUND)
1883 return atoi(StrSize.c_str());
1888 * \ingroup gdcmHeader
1889 * \brief Retrieve the number of Bits Stored
1890 * (as opposite to number of Bits Allocated)
1892 * @return The encountered number of Bits Stored, 0 by default.
1894 int gdcmHeader::GetBitsStored(void) {
1895 std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
1896 if (StrSize == GDCM_UNFOUND)
1898 return atoi(StrSize.c_str());
1903 * \ingroup gdcmHeader
1904 * \brief Retrieve the number of Samples Per Pixel
1905 * (1 : gray level, 3 : RGB)
1907 * @return The encountered number of Samples Per Pixel, 1 by default.
1909 int gdcmHeader::GetSamplesPerPixel(void) {
1910 std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
1911 if (StrSize == GDCM_UNFOUND)
1912 return 1; // Well, it's supposed to be mandatory ...
1913 return atoi(StrSize.c_str());
1917 * \ingroup gdcmHeader
1918 * \brief Retrieve the Planar Configuration for RGB images
1919 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1921 * @return The encountered Planar Configuration, 0 by default.
1923 int gdcmHeader::GetPlanarConfiguration(void) {
1924 std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
1925 if (StrSize == GDCM_UNFOUND)
1927 return atoi(StrSize.c_str());
1931 * \ingroup gdcmHeader
1932 * \brief Return the size (in bytes) of a single pixel of data.
1933 * @return The size in bytes of a single pixel of data.
1936 int gdcmHeader::GetPixelSize(void) {
1937 std::string PixelType = GetPixelType();
1938 if (PixelType == "8U" || PixelType == "8S")
1940 if (PixelType == "16U" || PixelType == "16S")
1942 if (PixelType == "32U" || PixelType == "32S")
1944 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1949 * \ingroup gdcmHeader
1950 * \brief Build the Pixel Type of the image.
1951 * Possible values are:
1952 * - 8U unsigned 8 bit,
1953 * - 8S signed 8 bit,
1954 * - 16U unsigned 16 bit,
1955 * - 16S signed 16 bit,
1956 * - 32U unsigned 32 bit,
1957 * - 32S signed 32 bit,
1958 * \warning 12 bit images appear as 16 bit.
1961 std::string gdcmHeader::GetPixelType(void) {
1962 std::string BitsAlloc;
1963 BitsAlloc = GetElValByName("Bits Allocated");
1964 if (BitsAlloc == GDCM_UNFOUND) {
1965 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1966 BitsAlloc = std::string("16");
1968 if (BitsAlloc == "12")
1969 BitsAlloc = std::string("16");
1972 Signed = GetElValByName("Pixel Representation");
1973 if (Signed == GDCM_UNFOUND) {
1974 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1975 BitsAlloc = std::string("0");
1978 Signed = std::string("U");
1980 Signed = std::string("S");
1982 return( BitsAlloc + Signed);
1986 * \ingroup gdcmHeader
1987 * \brief gets the info from 0002,0010 : Transfert Syntax
1989 * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
1991 std::string gdcmHeader::GetTransferSyntaxName(void) {
1992 std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
1993 if (TransfertSyntax == GDCM_UNFOUND) {
1994 dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
1995 return "Uncompressed ACR-NEMA";
1997 // we do it only when we need it
1998 gdcmTS * ts = gdcmGlobal::GetTS();
1999 std::string tsName=ts->GetValue(TransfertSyntax);
2000 //delete ts; // Seg Fault when deleted ?!
2004 // -------------------------------- Lookup Table related functions ------------
2007 * \ingroup gdcmHeader
2008 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2010 * @return Lookup Table Length
2011 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2014 int gdcmHeader::GetLUTLength(void) {
2015 std::vector<std::string> tokens;
2019 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2020 std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2021 if (LutDescriptionR == GDCM_UNFOUND)
2023 std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2024 if (LutDescriptionG == GDCM_UNFOUND)
2026 std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2027 if (LutDescriptionB == GDCM_UNFOUND)
2029 if( (LutDescriptionR != LutDescriptionG) || (LutDescriptionR != LutDescriptionB) ) {
2030 dbg.Verbose(0, "gdcmHeader::GetLUTLength: The CLUT R,G,B are not equal");
2033 std::cout << "Lut Description " << LutDescriptionR <<std::endl;
2034 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2035 Tokenize (LutDescriptionR, tokens, "\\");
2036 LutLength=atoi(tokens[0].c_str());
2037 //LutDepth=atoi(tokens[1].c_str());
2038 //LutNbits=atoi(tokens[2].c_str());
2044 * \ingroup gdcmHeader
2045 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2047 * @return Lookup Table nBit
2048 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2051 int gdcmHeader::GetLUTNbits(void) {
2052 std::vector<std::string> tokens;
2056 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2057 // Consistency already checked in GetLUTLength
2058 std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2059 if (LutDescription == GDCM_UNFOUND)
2061 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2062 Tokenize (LutDescription, tokens, "\\");
2063 //LutLength=atoi(tokens[0].c_str());
2064 //LutDepth=atoi(tokens[1].c_str());
2065 LutNbits=atoi(tokens[2].c_str());
2072 * \ingroup gdcmHeader
2073 * \brief gets the info from 0028,1201 : Lookup Table Red
2075 * @return Lookup Table Red
2076 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2078 void * gdcmHeader::GetLUTRed(void) {
2079 return GetPubElValVoidAreaByNumber(0x0028,0x1201);
2083 * \ingroup gdcmHeader
2084 * \brief gets the info from 0028,1202 : Lookup Table Green
2086 * @return Lookup Table Red
2087 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2089 void * gdcmHeader::GetLUTGreen(void) {
2090 return GetPubElValVoidAreaByNumber(0x0028,0x1202);
2094 * \ingroup gdcmHeader
2095 * \brief gets the info from 0028,1202 : Lookup Table Blue
2097 * @return Lookup Table Blue
2098 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2100 void * gdcmHeader::GetLUTBlue(void) {
2101 return GetPubElValVoidAreaByNumber(0x0028,0x1203);
2105 * \ingroup gdcmHeader
2107 * @return Lookup Table RGB
2108 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2109 * \ and (0028,1201),(0028,1202),(0028,1202) are found
2110 * \warning : hazardous ! Use better GetPubElValVoidAreaByNumber
2112 void * gdcmHeader::GetLUTRGB(void) {
2113 // Not so easy : see
2114 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2115 // and OT-PAL-8-face.dcm
2117 if (GetPubElValByNumber(0x0028,0x0004) == GDCM_UNFOUND) {
2118 dbg.Verbose(0, "gdcmHeader::GetLUTRGB: unfound Photometric Interpretation");
2121 void * LutR,*LutG,*LutB;
2124 // Maybe, some day we get an image
2125 // that respects the definition ...
2126 // Let's consider no ones does.
2131 int nBits=GetLUTNbits();
2132 // a virer quand on aura trouve UNE image
2133 // qui correspond VRAIMENT à la definition !
2134 std::cout << "l " << l << " nBits " << nBits;
2138 LutR =GetPubElValVoidAreaByNumber(0x0028,0x1201);
2139 LutG =GetPubElValVoidAreaByNumber(0x0028,0x1202);
2140 LutB =GetPubElValVoidAreaByNumber(0x0028,0x1203);
2142 // Warning : Any value for nBits as to be considered as 8
2143 // Any value for Length as to be considered as 256
2146 // Just wait before removing the following code
2149 guint16 * LUTRGB, *rgb;
2150 LUTRGB = rgb = (guint16 *) malloc(3*l*sizeof( guint16));
2151 guint16 * r = (guint16 *)LutR;
2152 guint16 * g = (guint16 *)LutG;
2153 guint16 * b = (guint16 *)LutB;
2154 for(int i=0;i<l;i++) {
2162 */ { // we assume it's always 8 Bits
2163 l=256; // we assume ...
2164 unsigned char * LUTRGB, *rgb;
2165 LUTRGB = rgb = (unsigned char *) malloc(3*l*sizeof( char));
2166 unsigned char * r = (unsigned char *)LutR;
2167 unsigned char * g = (unsigned char *)LutG;
2168 unsigned char * b = (unsigned char *)LutB;
2169 for(int i=0;i<l;i++) {
2170 //std::cout << "lut16 " << i << " : " << *r << " " << *g << " " << *b << std::endl;
2171 printf("lut 8 %d : %d %d %d \n",i,*r,*g,*b);
2176 free(LutR); free(LutB); free(LutG);