1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.97 2003/10/09 14:58:28 malaterre 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 // Sorry for the patch!
616 // XMedCom did the trick to read some nasty GE images ...
617 if (FoundLength == 13)
618 // The following 'if' will be removed when there is no more
619 // images on Creatis HD with a 13 length for Manufacturer...
620 if ( (ElVal->GetGroup() != 0x0008) || (ElVal->GetElement() ) )
621 // end of remove area
624 ElVal->SetLength(FoundLength);
628 * \ingroup gdcmHeader
633 guint32 gdcmHeader::FindLengthOB(void) {
634 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
637 long PositionOnEntry = ftell(fp);
638 bool FoundSequenceDelimiter = false;
639 guint32 TotalLength = 0;
642 while ( ! FoundSequenceDelimiter) {
650 TotalLength += 4; // We even have to decount the group and element
652 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
653 char msg[100]; // for sprintf. Sorry
654 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
655 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
660 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
661 FoundSequenceDelimiter = true;
662 else if ( n != 0xe000 ){
663 char msg[100]; // for sprintf. Sorry
664 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
666 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
670 ItemLength = ReadInt32();
671 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
672 // the ItemLength with ReadInt32
674 SkipBytes(ItemLength);
676 fseek(fp, PositionOnEntry, SEEK_SET);
681 * \ingroup gdcmHeader
686 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
687 guint16 element = ElVal->GetElement();
688 guint16 group = ElVal->GetGroup();
689 std::string vr = ElVal->GetVR();
691 if( (element == 0x0010) && (group == 0x7fe0) ) {
693 dbg.Verbose(2, "gdcmHeader::FindLength: ",
694 "we reached 7fe0 0010");
697 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
698 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
700 // The following reserved two bytes (see PS 3.5-2001, section
701 // 7.1.2 Data element structure with explicit vr p27) must be
702 // skipped before proceeding on reading the length on 4 bytes.
703 fseek(fp, 2L, SEEK_CUR);
705 guint32 length32 = ReadInt32();
707 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
708 ElVal->SetLength(FindLengthOB());
711 FixFoundLength(ElVal, length32);
715 // Length is encoded on 2 bytes.
716 length16 = ReadInt16();
718 // We can tell the current file is encoded in big endian (like
719 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
720 // and it's value is the one of the encoding of a big endian file.
721 // In order to deal with such big endian encoded files, we have
722 // (at least) two strategies:
723 // * when we load the "Transfer Syntax" tag with value of big endian
724 // encoding, we raise the proper flags. Then we wait for the end
725 // of the META group (0x0002) among which is "Transfer Syntax",
726 // before switching the swap code to big endian. We have to postpone
727 // the switching of the swap code since the META group is fully encoded
728 // in little endian, and big endian coding only starts at the next
729 // group. The corresponding code can be hard to analyse and adds
730 // many additional unnecessary tests for regular tags.
731 // * the second strategy consists in waiting for trouble, that shall
732 // appear when we find the first group with big endian encoding. This
733 // is easy to detect since the length of a "Group Length" tag (the
734 // ones with zero as element number) has to be of 4 (0x0004). When we
735 // encouter 1024 (0x0400) chances are the encoding changed and we
736 // found a group with big endian encoding.
737 // We shall use this second strategy. In order to make sure that we
738 // can interpret the presence of an apparently big endian encoded
739 // length of a "Group Length" without committing a big mistake, we
740 // add an additional check: we look in the already parsed elements
741 // for the presence of a "Transfer Syntax" whose value has to be "big
742 // endian encoding". When this is the case, chances are we have got our
743 // hands on a big endian encoded file: we switch the swap code to
744 // big endian and proceed...
745 if ( (element == 0x0000) && (length16 == 0x0400) ) {
746 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
747 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
752 SwitchSwapToBigEndian();
753 // Restore the unproperly loaded values i.e. the group, the element
754 // and the dictionary entry depending on them.
755 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
756 guint16 CorrectElem = SwapShort(ElVal->GetElement());
757 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
760 // This correct tag is not in the dictionary. Create a new one.
761 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
763 // FIXME this can create a memory leaks on the old entry that be
764 // left unreferenced.
765 ElVal->SetDictEntry(NewTag);
768 // Heuristic: well some files are really ill-formed.
769 if ( length16 == 0xffff) {
771 //dbg.Verbose(0, "gdcmHeader::FindLength",
772 // "Erroneous element length fixed.");
773 // Actually, length= 0xffff means that we deal with
774 // Unknown Sequence Length
777 FixFoundLength(ElVal, (guint32)length16);
781 // Either implicit VR or a non DICOM conformal (see not below) explicit
782 // VR that ommited the VR of (at least) this element. Farts happen.
783 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
784 // on Data elements "Implicit and Explicit VR Data Elements shall
785 // not coexist in a Data Set and Data Sets nested within it".]
786 // Length is on 4 bytes.
787 FixFoundLength(ElVal, ReadInt32());
791 * \ingroup gdcmHeader
792 * \brief Swaps back the bytes of 4-byte long integer accordingly to
795 * @return The suggested integer.
797 guint32 gdcmHeader::SwapLong(guint32 a) {
802 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
803 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
807 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
811 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
814 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
821 * \ingroup gdcmHeader
822 * \brief Swaps the bytes so they agree with the processor order
823 * @return The properly swaped 16 bits integer.
825 guint16 gdcmHeader::SwapShort(guint16 a) {
826 if ( (sw==4321) || (sw==2143) )
827 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
832 * \ingroup gdcmHeader
837 void gdcmHeader::SkipBytes(guint32 NBytes) {
838 //FIXME don't dump the returned value
839 (void)fseek(fp, (long)NBytes, SEEK_CUR);
843 * \ingroup gdcmHeader
848 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
849 SkipBytes(ElVal->GetLength());
853 * \ingroup gdcmHeader
858 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
861 if ((guint32)NewSize >= (guint32)0xffffffff) {
862 MaxSizeLoadElementValue = 0xffffffff;
865 MaxSizeLoadElementValue = NewSize;
869 * \ingroup gdcmHeader
870 * \brief Loads the element content if it's length is not bigger
871 * than the value specified with
872 * gdcmHeader::SetMaxSizeLoadElementValue()
874 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
876 guint16 group = ElVal->GetGroup();
877 std::string vr= ElVal->GetVR();
878 guint32 length = ElVal->GetLength();
879 bool SkipLoad = false;
881 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
883 // FIXME Sequences not treated yet !
885 // Ne faudrait-il pas au contraire trouver immediatement
886 // une maniere 'propre' de traiter les sequences (vr = SQ)
887 // car commencer par les ignorer risque de conduire a qq chose
888 // qui pourrait ne pas etre generalisable
889 // Well, I'm expecting your code !!!
894 // Heuristic : a sequence "contains" a set of tags (called items). It looks
895 // like the last tag of a sequence (the one that terminates the sequence)
896 // has a group of 0xfffe (with a dummy length).
898 // Actually (fffe e000) tells us an Element is beginning
899 // (fffe e00d) tells us an Element just ended
900 // (fffe e0dd) tells us the current SEQuence just ended
902 if( group == 0xfffe )
907 ElVal->SetValue("gdcm::Skipped");
911 // When the length is zero things are easy:
917 // The elements whose length is bigger than the specified upper bound
918 // are not loaded. Instead we leave a short notice of the offset of
919 // the element content and it's length.
920 if (length > MaxSizeLoadElementValue) {
921 std::ostringstream s;
922 s << "gdcm::NotLoaded.";
923 s << " Address:" << (long)ElVal->GetOffset();
924 s << " Length:" << ElVal->GetLength();
925 ElVal->SetValue(s.str());
929 // When an integer is expected, read and convert the following two or
930 // four bytes properly i.e. as an integer as opposed to a string.
932 // pour les elements de Value Multiplicity > 1
933 // on aura en fait une serie d'entiers
934 // on devrait pouvoir faire + compact (?)
936 if ( IsAnInteger(ElVal) ) {
938 std::ostringstream s;
940 if (vr == "US" || vr == "SS") {
942 NewInt = ReadInt16();
945 for (int i=1; i < nbInt; i++) {
947 NewInt = ReadInt16();
952 } else if (vr == "UL" || vr == "SL") {
954 NewInt = ReadInt32();
957 for (int i=1; i < nbInt; i++) {
959 NewInt = ReadInt32();
964 ElVal->SetValue(s.str());
968 // We need an additional byte for storing \0 that is not on disk
969 char* NewValue = (char*)malloc(length+1);
971 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
976 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
977 if ( item_read != 1 ) {
979 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
980 ElVal->SetValue("gdcm::UnRead");
983 ElVal->SetValue(NewValue);
988 * \ingroup gdcmHeader
989 * \brief Loads the element while preserving the current
990 * underlying file position indicator as opposed to
991 * to LoadElementValue that modifies it.
992 * @param ElVal Element whose value shall be loaded.
995 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
996 long PositionOnEntry = ftell(fp);
997 LoadElementValue(ElVal);
998 fseek(fp, PositionOnEntry, SEEK_SET);
1002 * \ingroup gdcmHeader
1003 * \brief Reads a supposed to be 16 Bits integer
1004 * \ (swaps it depending on processor endianity)
1006 * @return integer acts as a boolean
1008 guint16 gdcmHeader::ReadInt16(void) {
1011 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1012 if ( item_read != 1 ) {
1013 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1015 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1017 dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1027 * \ingroup gdcmHeader
1028 * \brief Reads a supposed to be 32 Bits integer
1029 * \ (swaps it depending on processor endianity)
1033 guint32 gdcmHeader::ReadInt32(void) {
1036 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1037 if ( item_read != 1 ) {
1038 //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1040 // dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1042 dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");
1052 * \ingroup gdcmHeader
1057 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1059 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1061 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1062 "failed to Locate gdcmElValue");
1063 return (gdcmElValue*)0;
1069 * \ingroup gdcmHeader
1070 * \brief Build a new Element Value from all the low level arguments.
1071 * Check for existence of dictionary entry, and build
1072 * a default one when absent.
1073 * @param Group group of the underlying DictEntry
1074 * @param Elem element of the underlying DictEntry
1076 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1077 // Find out if the tag we encountered is in the dictionaries:
1078 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1080 NewTag = new gdcmDictEntry(Group, Elem);
1082 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1084 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1085 "failed to allocate gdcmElValue");
1086 return (gdcmElValue*)0;
1092 * \ingroup gdcmHeader
1097 * \return integer acts as a boolean
1099 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value,
1100 guint16 Group, guint16 Elem ) {
1102 // TODO : FIXME JPRx
1104 // on (je) cree une Elvalue ne contenant pas de valeur
1105 // on l'ajoute au ElValSet
1106 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1107 // --> devrait pouvoir etre fait + simplement ???
1108 if (CheckIfExistByNumber(Group, Elem) == 0) {
1109 gdcmElValue* a =NewElValueByNumber(Group, Elem);
1114 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1120 * \ingroup gdcmHeader
1121 * \brief Modify (or Creates if not found) an element
1122 * @param Value new value
1125 * \return integer acts as a boolean
1128 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1130 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1131 PubElValSet.Add(nvElValue);
1132 std::string v = Value;
1133 PubElValSet.SetElValueByNumber(v, Group, Elem);
1139 * \ingroup gdcmHeader
1140 * \brief Set a new value if the invoked element exists
1144 * \return integer acts as a boolean
1146 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1148 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1149 std::string v = Value;
1150 PubElValSet.SetElValueByNumber(v, Group, Elem);
1156 * \ingroup gdcmHeader
1157 * \brief Checks if a given ElValue (group,number)
1158 * \ exists in the Public ElValSet
1161 * @return integer acts as a boolean
1164 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1165 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1169 * \ingroup gdcmHeader
1170 * \brief Build a new Element Value from all the low level arguments.
1171 * Check for existence of dictionary entry, and build
1172 * a default one when absent.
1173 * @param Name Name of the underlying DictEntry
1175 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1177 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1179 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1181 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1183 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1184 "failed to allocate gdcmElValue");
1185 return (gdcmElValue*)0;
1191 * \ingroup gdcmHeader
1192 * \brief Read the next tag but WITHOUT loading it's value
1193 * @return On succes the newly created ElValue, NULL on failure.
1195 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1198 gdcmElValue * NewElVal;
1204 // We reached the EOF (or an error occured) and header parsing
1205 // has to be considered as finished.
1206 return (gdcmElValue *)0;
1208 NewElVal = NewElValueByNumber(g, n);
1210 FindLength(NewElVal);
1213 return (gdcmElValue *)0;
1215 NewElVal->SetOffset(ftell(fp));
1216 //if ( (g==0x7fe0) && (n==0x0010) )
1221 * \ingroup gdcmHeader
1222 * \brief Apply some heuristics to predict wether the considered
1223 * element value contains/represents an integer or not.
1224 * @param ElVal The element value on which to apply the predicate.
1225 * @return The result of the heuristical predicate.
1227 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1228 guint16 group = ElVal->GetGroup();
1229 guint16 element = ElVal->GetElement();
1230 std::string vr = ElVal->GetVR();
1231 guint32 length = ElVal->GetLength();
1233 // When we have some semantics on the element we just read, and if we
1234 // a priori know we are dealing with an integer, then we shall be
1235 // able to swap it's element value properly.
1236 if ( element == 0 ) { // This is the group length of the group
1240 dbg.Error("gdcmHeader::IsAnInteger",
1241 "Erroneous Group Length element length.");
1244 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1251 * \ingroup gdcmHeader
1252 * \brief Recover the offset (from the beginning of the file) of the pixels.
1254 size_t gdcmHeader::GetPixelOffset(void) {
1255 // If this file complies with the norm we should encounter the
1256 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1257 // the group that contains the pixel data (hence the "Pixel Data"
1258 // is found by indirection through the "Image Location").
1259 // Inside the group pointed by "Image Location" the searched element
1260 // is conventionally the element 0x0010 (when the norm is respected).
1261 // When the "Image Location" is absent we default to group 0x7fe0.
1264 std::string ImageLocation = GetPubElValByName("Image Location");
1265 if ( ImageLocation == GDCM_UNFOUND ) {
1268 grPixel = (guint16) atoi( ImageLocation.c_str() );
1270 if (grPixel != 0x7fe0)
1271 // This is a kludge for old dirty Philips imager.
1276 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1279 return PixelElement->GetOffset();
1285 * \ingroup gdcmHeader
1286 * \brief Searches both the public and the shadow dictionary (when they
1287 * exist) for the presence of the DictEntry with given
1288 * group and element. The public dictionary has precedence on the
1290 * @param group group of the searched DictEntry
1291 * @param element element of the searched DictEntry
1292 * @return Corresponding DictEntry when it exists, NULL otherwise.
1294 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1296 gdcmDictEntry * found = (gdcmDictEntry*)0;
1297 if (!RefPubDict && !RefShaDict) {
1298 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1299 "we SHOULD have a default dictionary");
1302 found = RefPubDict->GetTagByNumber(group, element);
1307 found = RefShaDict->GetTagByNumber(group, element);
1315 * \ingroup gdcmHeader
1316 * \brief Searches both the public and the shadow dictionary (when they
1317 * exist) for the presence of the DictEntry with given name.
1318 * The public dictionary has precedence on the shadow one.
1319 * @param Name name of the searched DictEntry
1320 * @return Corresponding DictEntry when it exists, NULL otherwise.
1322 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1323 gdcmDictEntry * found = (gdcmDictEntry*)0;
1324 if (!RefPubDict && !RefShaDict) {
1325 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1326 "we SHOULD have a default dictionary");
1329 found = RefPubDict->GetTagByName(Name);
1334 found = RefShaDict->GetTagByName(Name);
1342 * \ingroup gdcmHeader
1343 * \brief Searches within the public dictionary for element value of
1345 * @param group Group of the researched tag.
1346 * @param element Element of the researched tag.
1347 * @return Corresponding element value when it exists, and the string
1348 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1350 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1351 return PubElValSet.GetElValueByNumber(group, element);
1355 * \ingroup gdcmHeader
1356 * \brief Searches within the public dictionary for element value
1357 * representation of a given tag.
1359 * Obtaining the VR (Value Representation) might be needed by caller
1360 * to convert the string typed content to caller's native type
1361 * (think of C++ vs Python). The VR is actually of a higher level
1362 * of semantics than just the native C++ type.
1363 * @param group Group of the researched tag.
1364 * @param element Element of the researched tag.
1365 * @return Corresponding element value representation when it exists,
1366 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1368 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1369 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1371 return GDCM_UNFOUND;
1372 return elem->GetVR();
1376 * \ingroup gdcmHeader
1377 * \brief Searches within the public dictionary for element value of
1379 * @param TagName name of the researched element.
1380 * @return Corresponding element value when it exists, and the string
1381 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1383 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1384 return PubElValSet.GetElValueByName(TagName);
1388 * \ingroup gdcmHeader
1389 * \brief Searches within the elements parsed with the public dictionary for
1390 * the element value representation of a given tag.
1392 * Obtaining the VR (Value Representation) might be needed by caller
1393 * to convert the string typed content to caller's native type
1394 * (think of C++ vs Python). The VR is actually of a higher level
1395 * of semantics than just the native C++ type.
1396 * @param TagName name of the researched element.
1397 * @return Corresponding element value representation when it exists,
1398 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1400 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1401 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1403 return GDCM_UNFOUND;
1404 return elem->GetVR();
1408 * \ingroup gdcmHeader
1409 * \brief Searches within elements parsed with the SHADOW dictionary
1410 * for the element value of a given tag.
1411 * @param group Group of the researched tag.
1412 * @param element Element of the researched tag.
1413 * @return Corresponding element value representation when it exists,
1414 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1416 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1417 return ShaElValSet.GetElValueByNumber(group, element);
1421 * \ingroup gdcmHeader
1422 * \brief Searches within the elements parsed with the SHADOW dictionary
1423 * for the element value representation of a given tag.
1425 * Obtaining the VR (Value Representation) might be needed by caller
1426 * to convert the string typed content to caller's native type
1427 * (think of C++ vs Python). The VR is actually of a higher level
1428 * of semantics than just the native C++ type.
1429 * @param group Group of the researched tag.
1430 * @param element Element of the researched tag.
1431 * @return Corresponding element value representation when it exists,
1432 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1434 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1435 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1437 return GDCM_UNFOUND;
1438 return elem->GetVR();
1442 * \ingroup gdcmHeader
1443 * \brief Searches within the elements parsed with the shadow dictionary
1444 * for an element value of given tag.
1445 * @param TagName name of the researched element.
1446 * @return Corresponding element value when it exists, and the string
1447 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1449 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1450 return ShaElValSet.GetElValueByName(TagName);
1454 * \ingroup gdcmHeader
1455 * \brief Searches within the elements parsed with the shadow dictionary for
1456 * the element value representation of a given tag.
1458 * Obtaining the VR (Value Representation) might be needed by caller
1459 * to convert the string typed content to caller's native type
1460 * (think of C++ vs Python). The VR is actually of a higher level
1461 * of semantics than just the native C++ type.
1462 * @param TagName name of the researched element.
1463 * @return Corresponding element value representation when it exists,
1464 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1466 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1467 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1469 return GDCM_UNFOUND;
1470 return elem->GetVR();
1474 * \ingroup gdcmHeader
1475 * \brief Searches within elements parsed with the public dictionary
1476 * and then within the elements parsed with the shadow dictionary
1477 * for the element value of a given tag.
1478 * @param group Group of the researched tag.
1479 * @param element Element of the researched tag.
1480 * @return Corresponding element value representation when it exists,
1481 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1483 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1484 std::string pub = GetPubElValByNumber(group, element);
1487 return GetShaElValByNumber(group, element);
1491 * \ingroup gdcmHeader
1492 * \brief Searches within elements parsed with the public dictionary
1493 * and then within the elements parsed with the shadow dictionary
1494 * for the element value representation of a given tag.
1496 * Obtaining the VR (Value Representation) might be needed by caller
1497 * to convert the string typed content to caller's native type
1498 * (think of C++ vs Python). The VR is actually of a higher level
1499 * of semantics than just the native C++ type.
1500 * @param group Group of the researched tag.
1501 * @param element Element of the researched tag.
1502 * @return Corresponding element value representation when it exists,
1503 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1505 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1506 std::string pub = GetPubElValRepByNumber(group, element);
1509 return GetShaElValRepByNumber(group, element);
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 of a given tag.
1517 * @param TagName name of the researched element.
1518 * @return Corresponding element value when it exists,
1519 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1521 std::string gdcmHeader::GetElValByName(std::string TagName) {
1522 std::string pub = GetPubElValByName(TagName);
1525 return GetShaElValByName(TagName);
1529 * \ingroup gdcmHeader
1530 * \brief Searches within elements parsed with the public dictionary
1531 * and then within the elements parsed with the shadow dictionary
1532 * for the element value representation of a given tag.
1534 * Obtaining the VR (Value Representation) might be needed by caller
1535 * to convert the string typed content to caller's native type
1536 * (think of C++ vs Python). The VR is actually of a higher level
1537 * of semantics than just the native C++ type.
1538 * @param TagName name of the researched element.
1539 * @return Corresponding element value representation when it exists,
1540 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1542 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1543 std::string pub = GetPubElValRepByName(TagName);
1546 return GetShaElValRepByName(TagName);
1550 * \ingroup gdcmHeader
1551 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1552 * through it's (group, element) and modifies it's content with
1554 * @param content new value to substitute with
1555 * @param group group of the ElVal to modify
1556 * @param element element of the ElVal to modify
1558 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1561 //TODO : homogeneiser les noms : SetPubElValByNumber
1562 // qui appelle PubElValSet.SetElValueByNumber
1563 // pourquoi pas SetPubElValueByNumber ??
1566 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1570 * \ingroup gdcmHeader
1571 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1572 * through tag name and modifies it's content with the given value.
1573 * @param content new value to substitute with
1574 * @param TagName name of the tag to be modified
1576 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1577 return ( PubElValSet.SetElValueByName (content, TagName) );
1581 * \ingroup gdcmHeader
1582 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1583 * through it's (group, element) and modifies it's length with
1585 * \warning Use with extreme caution.
1586 * @param length new length 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.
1592 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1594 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1598 * \ingroup gdcmHeader
1599 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1600 * through it's (group, element) and modifies it's content with
1602 * @param content new value to substitute with
1603 * @param group group of the ElVal to modify
1604 * @param element element of the ElVal to modify
1605 * @return 1 on success, 0 otherwise.
1607 int gdcmHeader::SetShaElValByNumber(std::string content,
1608 guint16 group, guint16 element) {
1609 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1613 * \ingroup gdcmHeader
1614 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1615 * through tag name and modifies it's content with the given value.
1616 * @param content new value to substitute with
1617 * @param ShadowTagName name of the tag to be modified
1619 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1620 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1624 * \ingroup gdcmHeader
1625 * \brief Parses the header of the file but WITHOUT loading element values.
1627 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1628 gdcmElValue * newElValue = (gdcmElValue *)0;
1632 while ( (newElValue = ReadNextElement()) ) {
1633 SkipElementValue(newElValue);
1634 PubElValSet.Add(newElValue);
1639 * \ingroup gdcmHeader
1640 * \brief This predicate, based on hopefully reasonnable heuristics,
1641 * decides whether or not the current gdcmHeader was properly parsed
1642 * and contains the mandatory information for being considered as
1643 * a well formed and usable image.
1644 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1647 bool gdcmHeader::IsReadable(void) {
1648 if ( GetElValByName("Image Dimensions") != GDCM_UNFOUND
1649 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1652 if ( GetElValByName("Bits Allocated") == GDCM_UNFOUND )
1654 if ( GetElValByName("Bits Stored") == GDCM_UNFOUND )
1656 if ( GetElValByName("High Bit") == GDCM_UNFOUND )
1658 if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1664 * \ingroup gdcmHeader
1665 * \brief Small utility function that creates a new manually crafted
1666 * (as opposed as read from the file) gdcmElValue with user
1667 * specified name and adds it to the public tag hash table.
1668 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1669 * @param NewTagName The name to be given to this new tag.
1670 * @param VR The Value Representation to be given to this new tag.
1671 * @ return The newly hand crafted Element Value.
1673 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName,
1675 gdcmElValue* NewElVal = (gdcmElValue*)0;
1676 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1677 guint32 FreeElem = 0;
1678 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1680 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1681 if (FreeElem == UINT32_MAX) {
1682 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1683 "Group 0xffff in Public Dict is full");
1684 return (gdcmElValue*)0;
1686 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1687 VR, "GDCM", NewTagName);
1688 NewElVal = new gdcmElValue(NewEntry);
1689 PubElValSet.Add(NewElVal);
1694 * \ingroup gdcmHeader
1695 * \brief Loads the element values of all the elements present in the
1696 * public tag based hash table.
1698 void gdcmHeader::LoadElements(void) {
1700 TagElValueHT ht = PubElValSet.GetTagHt();
1701 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1702 LoadElementValue(tag->second);
1706 // Load 'non string' values
1707 std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);
1708 if( PhotometricInterpretation == "PALETTE COLOR " ){
1709 LoadElementVoidArea(0x0028,0x1200); // gray LUT
1710 LoadElementVoidArea(0x0028,0x1201); // R LUT
1711 LoadElementVoidArea(0x0028,0x1202); // G LUT
1712 LoadElementVoidArea(0x0028,0x1203); // B LUT
1714 LoadElementVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1715 LoadElementVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1716 LoadElementVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1719 // --------------------------------------------------------------
1720 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1722 // if recognition code tells us we deal with a LibIDO image
1723 // we switch lineNumber and columnNumber
1725 std::string RecCode;
1726 RecCode = GetPubElValByNumber(0x0008, 0x0010);
1727 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1728 RecCode == "CANRME_AILIBOD1_1." ) {
1729 filetype = ACR_LIBIDO;
1730 std::string rows = GetPubElValByNumber(0x0028, 0x0010);
1731 std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1732 SetPubElValByNumber(columns, 0x0028, 0x0010);
1733 SetPubElValByNumber(rows , 0x0028, 0x0011);
1735 // ----------------- End of Special Patch ----------------
1739 * \ingroup gdcmHeader
1743 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1744 PubElValSet.Print(os);
1748 * \ingroup gdcmHeader
1752 void gdcmHeader::PrintPubDict(std::ostream & os) {
1753 RefPubDict->Print(os);
1757 * \ingroup gdcmHeader
1761 int gdcmHeader::Write(FILE * fp, FileType type) {
1764 // TODO : move the following lines (and a lot of others)
1765 // to a future function CheckAndCorrectHeader
1767 if (type == ImplicitVR) {
1768 std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
1769 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
1771 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1772 // values with a VR of UI shall be padded with a single trailing null
1773 // Dans le cas suivant on doit pader manuellement avec un 0
1775 PubElValSet.SetElValueLengthByNumber(18, 0x0002, 0x0010);
1778 if (type == ExplicitVR) {
1779 std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
1780 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
1782 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1783 // values with a VR of UI shall be padded with a single trailing null
1784 // Dans le cas suivant on doit pader manuellement avec un 0
1786 PubElValSet.SetElValueLengthByNumber(20, 0x0002, 0x0010);
1789 return PubElValSet.Write(fp, type);
1793 // ------------------------ 'non string' elements related functions
1797 * \ingroup gdcmHeader
1798 * \brief Loads (from disk) the element content
1799 * when a string is not suitable
1801 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1802 gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1805 size_t o =(size_t)Element->GetOffset();
1806 fseek(fp, o, SEEK_SET);
1807 int l=Element->GetLength();
1808 void * a = malloc(l);
1810 std::cout << "Big Broblem (LoadElementVoidArea, malloc) "
1811 << std::hex << Group << " " << Elem << std::endl;
1814 int res = PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1815 // TODO check the result
1816 size_t l2 = fread(a, 1, l ,fp);
1818 std::cout << "Big Broblem (LoadElementVoidArea, fread) "
1819 << std::hex << Group << " " << Elem << std::endl;
1826 * \ingroup gdcmHeader
1827 * \brief Gets (from Header) the offset of a 'non string' element value
1828 * \ (LoadElementValue has already be executed)
1831 * @return File Offset of the Element Value
1833 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1834 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1836 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1837 "failed to Locate gdcmElValue");
1840 return elValue->GetOffset();
1844 * \ingroup gdcmHeader
1845 * \brief Gets (from Header) a 'non string' element value
1846 * \ (LoadElementValue has already be executed)
1849 * @return Pointer to the 'non string' area
1852 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1853 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1855 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1856 "failed to Locate gdcmElValue");
1859 return elValue->GetVoidArea();
1864 // =============================================================================
1865 // Heuristics based accessors
1866 //==============================================================================
1869 // TODO : move to an other file.
1873 * \ingroup gdcmHeader
1874 * \brief Retrieve the number of columns of image.
1875 * @return The encountered size when found, 0 by default.
1877 int gdcmHeader::GetXSize(void) {
1878 // We cannot check for "Columns" because the "Columns" tag is present
1879 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1880 std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1881 if (StrSize == GDCM_UNFOUND)
1883 return atoi(StrSize.c_str());
1887 * \ingroup gdcmHeader
1888 * \brief Retrieve the number of lines of image.
1889 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1890 * @return The encountered size when found, 1 by default.
1892 int gdcmHeader::GetYSize(void) {
1893 // We cannot check for "Rows" because the "Rows" tag is present
1894 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1895 std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1896 if (StrSize != GDCM_UNFOUND)
1897 return atoi(StrSize.c_str());
1901 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1902 // hence be a signal (1d image). So we default to 1:
1907 * \ingroup gdcmHeader
1908 * \brief Retrieve the number of planes of volume or the number
1909 * of frames of a multiframe.
1910 * \warning When present we consider the "Number of Frames" as the third
1911 * dimension. When absent we consider the third dimension as
1912 * being the "Planes" tag content.
1913 * @return The encountered size when found, 1 by default.
1915 int gdcmHeader::GetZSize(void) {
1916 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1917 // as the third dimension.
1918 std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
1919 if (StrSize != GDCM_UNFOUND)
1920 return atoi(StrSize.c_str());
1922 // We then consider the "Planes" entry as the third dimension [we
1923 // cannot retrieve by name since "Planes tag is present both in
1924 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1925 StrSize = GetPubElValByNumber(0x0028,0x0012);
1926 if (StrSize != GDCM_UNFOUND)
1927 return atoi(StrSize.c_str());
1932 * \ingroup gdcmHeader
1933 * \brief Retrieve the number of Bits Stored
1934 * (as opposite to number of Bits Allocated)
1936 * @return The encountered number of Bits Stored, 0 by default.
1938 int gdcmHeader::GetBitsStored(void) {
1939 std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
1940 if (StrSize == GDCM_UNFOUND)
1942 return atoi(StrSize.c_str());
1947 * \ingroup gdcmHeader
1948 * \brief Retrieve the number of Samples Per Pixel
1949 * (1 : gray level, 3 : RGB)
1951 * @return The encountered number of Samples Per Pixel, 1 by default.
1953 int gdcmHeader::GetSamplesPerPixel(void) {
1954 std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
1955 if (StrSize == GDCM_UNFOUND)
1956 return 1; // Well, it's supposed to be mandatory ...
1957 return atoi(StrSize.c_str());
1961 * \ingroup gdcmHeader
1962 * \brief Retrieve the Planar Configuration for RGB images
1963 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1965 * @return The encountered Planar Configuration, 0 by default.
1967 int gdcmHeader::GetPlanarConfiguration(void) {
1968 std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
1969 if (StrSize == GDCM_UNFOUND)
1971 return atoi(StrSize.c_str());
1975 * \ingroup gdcmHeader
1976 * \brief Return the size (in bytes) of a single pixel of data.
1977 * @return The size in bytes of a single pixel of data.
1980 int gdcmHeader::GetPixelSize(void) {
1981 std::string PixelType = GetPixelType();
1982 if (PixelType == "8U" || PixelType == "8S")
1984 if (PixelType == "16U" || PixelType == "16S")
1986 if (PixelType == "32U" || PixelType == "32S")
1988 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1993 * \ingroup gdcmHeader
1994 * \brief Build the Pixel Type of the image.
1995 * Possible values are:
1996 * - 8U unsigned 8 bit,
1997 * - 8S signed 8 bit,
1998 * - 16U unsigned 16 bit,
1999 * - 16S signed 16 bit,
2000 * - 32U unsigned 32 bit,
2001 * - 32S signed 32 bit,
2002 * \warning 12 bit images appear as 16 bit.
2005 std::string gdcmHeader::GetPixelType(void) {
2006 std::string BitsAlloc;
2007 BitsAlloc = GetElValByName("Bits Allocated");
2008 if (BitsAlloc == GDCM_UNFOUND) {
2009 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
2010 BitsAlloc = std::string("16");
2012 if (BitsAlloc == "12")
2013 BitsAlloc = std::string("16");
2016 Signed = GetElValByName("Pixel Representation");
2017 if (Signed == GDCM_UNFOUND) {
2018 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
2019 BitsAlloc = std::string("0");
2022 Signed = std::string("U");
2024 Signed = std::string("S");
2026 return( BitsAlloc + Signed);
2030 * \ingroup gdcmHeader
2031 * \brief gets the info from 0002,0010 : Transfert Syntax
2033 * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
2035 std::string gdcmHeader::GetTransferSyntaxName(void) {
2036 std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
2037 if (TransfertSyntax == GDCM_UNFOUND) {
2038 dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
2039 return "Uncompressed ACR-NEMA";
2041 // we do it only when we need it
2042 gdcmTS * ts = gdcmGlobal::GetTS();
2043 std::string tsName=ts->GetValue(TransfertSyntax);
2044 //delete ts; // Seg Fault when deleted ?!
2048 // -------------------------------- Lookup Table related functions ------------
2051 * \ingroup gdcmHeader
2052 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2054 * @return Lookup Table Length
2055 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2058 int gdcmHeader::GetLUTLength(void) {
2059 std::vector<std::string> tokens;
2063 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2064 std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2065 if (LutDescriptionR == GDCM_UNFOUND)
2067 std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2068 if (LutDescriptionG == GDCM_UNFOUND)
2070 std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2071 if (LutDescriptionB == GDCM_UNFOUND)
2073 if( (LutDescriptionR != LutDescriptionG) || (LutDescriptionR != LutDescriptionB) ) {
2074 dbg.Verbose(0, "gdcmHeader::GetLUTLength: The CLUT R,G,B are not equal");
2077 std::cout << "Lut Description " << LutDescriptionR <<std::endl;
2078 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2079 Tokenize (LutDescriptionR, tokens, "\\");
2080 LutLength=atoi(tokens[0].c_str());
2081 //LutDepth=atoi(tokens[1].c_str());
2082 //LutNbits=atoi(tokens[2].c_str());
2088 * \ingroup gdcmHeader
2089 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2091 * @return Lookup Table nBit
2092 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2095 int gdcmHeader::GetLUTNbits(void) {
2096 std::vector<std::string> tokens;
2100 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2101 // Consistency already checked in GetLUTLength
2102 std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2103 if (LutDescription == GDCM_UNFOUND)
2105 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2106 Tokenize (LutDescription, tokens, "\\");
2107 //LutLength=atoi(tokens[0].c_str());
2108 //LutDepth=atoi(tokens[1].c_str());
2109 LutNbits=atoi(tokens[2].c_str());
2116 * \ingroup gdcmHeader
2117 * \brief gets the info from 0028,1201 : Lookup Table Red
2119 * @return Lookup Table Red
2120 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2122 void * gdcmHeader::GetLUTRed(void) {
2123 return GetPubElValVoidAreaByNumber(0x0028,0x1201);
2127 * \ingroup gdcmHeader
2128 * \brief gets the info from 0028,1202 : Lookup Table Green
2130 * @return Lookup Table Red
2131 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2133 void * gdcmHeader::GetLUTGreen(void) {
2134 return GetPubElValVoidAreaByNumber(0x0028,0x1202);
2138 * \ingroup gdcmHeader
2139 * \brief gets the info from 0028,1202 : Lookup Table Blue
2141 * @return Lookup Table Blue
2142 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2144 void * gdcmHeader::GetLUTBlue(void) {
2145 return GetPubElValVoidAreaByNumber(0x0028,0x1203);
2149 * \ingroup gdcmHeader
2151 * @return Lookup Table RGB
2152 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2153 * \ and (0028,1201),(0028,1202),(0028,1202) are found
2154 * \warning : hazardous ! Use better GetPubElValVoidAreaByNumber
2156 void * gdcmHeader::GetLUTRGB(void) {
2157 // Not so easy : see
2158 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2159 // and OT-PAL-8-face.dcm
2161 if (GetPubElValByNumber(0x0028,0x0004) == GDCM_UNFOUND) {
2162 dbg.Verbose(0, "gdcmHeader::GetLUTRGB: unfound Photometric Interpretation");
2165 void * LutR,*LutG,*LutB;
2168 // Maybe, some day we get an image
2169 // that respects the definition ...
2170 // Let's consider no ones does.
2175 int nBits=GetLUTNbits();
2177 // a virer quand on aura trouve UNE image
2178 // qui correspond VRAIMENT à la definition !
2179 std::cout << "l " << l << " nBits " << nBits;
2183 LutR =GetPubElValVoidAreaByNumber(0x0028,0x1201);
2184 LutG =GetPubElValVoidAreaByNumber(0x0028,0x1202);
2185 LutB =GetPubElValVoidAreaByNumber(0x0028,0x1203);
2187 // Warning : Any value for nBits as to be considered as 8
2188 // Any value for Length as to be considered as 256
2191 // Just wait before removing the following code
2194 guint16 * LUTRGB, *rgb;
2195 LUTRGB = rgb = (guint16 *) malloc(3*l*sizeof( guint16));
2196 guint16 * r = (guint16 *)LutR;
2197 guint16 * g = (guint16 *)LutG;
2198 guint16 * b = (guint16 *)LutB;
2199 for(int i=0;i<l;i++) {
2207 */ { // we assume it's always 8 Bits
2208 l=256; // we assume ...
2209 unsigned char * LUTRGB, *rgb;
2210 LUTRGB = rgb = (unsigned char *) malloc(3*l*sizeof( char));
2211 unsigned char * r = (unsigned char *)LutR;
2212 unsigned char * g = (unsigned char *)LutG;
2213 unsigned char * b = (unsigned char *)LutB;
2214 for(int i=0;i<l;i++) {
2215 //std::cout << "lut16 " << i << " : " << *r << " " << *g << " " << *b
2217 printf("lut 8 %d : %d %d %d \n",i,*r,*g,*b);
2222 free(LutR); free(LutB); free(LutG);
2226 /* Sorry for the comments. The code will be moved in a fonction
2228 std::string x=GetPubElValByNumber(0x0028,0x1201);
2229 unsigned short int * lutR = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2230 unsigned short int * lutG = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2231 unsigned short int * lutB = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2233 std::vector<std::string> tokens;
2234 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2235 Tokenize ((const std::string)x, tokens, "\\");
2236 for (unsigned int i=0; i<tokens.size();i++) {
2237 lutR[i] = atoi(tokens[i].c_str());
2238 printf("%d (%x)\n",lutR[i],lutR[i]);
2241 std::string y=GetPubElValByNumber(0x0028,0x1202);
2242 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2243 Tokenize ((const std::string)y, tokens, "\\");
2244 for (unsigned int i=0; i<tokens.size();i++) {
2245 lutG[i] = atoi(tokens[i].c_str());
2248 std::string z=GetPubElValByNumber(0x0028,0x1203);
2249 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2250 Tokenize ((const std::string)z, tokens, "\\");
2251 for (unsigned int i=0; i<tokens.size();i++) {
2252 lutB[i] = atoi(tokens[i].c_str());
2254 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2255 Tokenize ((const std::string)x, tokens, "\\");
2256 for (unsigned int i=0; i<tokens.size();i++) {
2257 lutB[i] = atoi(tokens[i].c_str());
2262 //int lgth=GetLUTLength();
2263 //cout << "lgth " << lgth << std::endl;;
2264 //for (int j=0;j<lgth;j++){
2265 //printf ("%d : %d (%x) %d (%x) %d (%x)\n",j,lutR[j],lutR[j],lutG[j],lutG[j],lutB[j],lutB[j]);