1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.92 2003/10/02 11:26:15 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;
499 * \ingroup gdcmHeader
500 * \brief Determines if the Transfer Syntax was already encountered
501 * and if it corresponds to a JPEGExtendedProcess2-4 one.
503 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
505 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
506 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
509 LoadElementValueSafe(Element);
510 std::string Transfer = Element->GetValue();
511 if ( Transfer == "1.2.840.10008.1.2.4.51" )
517 * \ingroup gdcmHeader
518 * \brief Determines if the Transfer Syntax was already encountered
519 * and if it corresponds to a JPEGExtendeProcess3-5 one.
521 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
523 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
524 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
527 LoadElementValueSafe(Element);
528 std::string Transfer = Element->GetValue();
529 if ( Transfer == "1.2.840.10008.1.2.4.52" )
535 * \ingroup gdcmHeader
536 * \brief Determines if the Transfer Syntax was already encountered
537 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
539 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
542 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
543 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
546 LoadElementValueSafe(Element);
547 std::string Transfer = Element->GetValue();
548 if ( Transfer == "1.2.840.10008.1.2.4.53" )
554 * \ingroup gdcmHeader
555 * \brief Determines if the Transfer Syntax was already encountered
556 * and if it corresponds to a RLE Lossless one.
558 * @return True when RLE Lossless found. False in all
561 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
562 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
565 LoadElementValueSafe(Element);
566 std::string Transfer = Element->GetValue();
567 if ( Transfer == "1.2.840.10008.1.2.5" )
573 * \ingroup gdcmHeader
574 * \brief Determines if the Transfer Syntax was already encountered
575 * and if it corresponds to a JPEG200 one.0
577 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
580 bool gdcmHeader::IsJPEG2000(void) {
581 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
584 LoadElementValueSafe(Element);
585 std::string Transfer = Element->GetValue();
586 if ( (Transfer == "1.2.840.10008.1.2.4.90")
587 || (Transfer == "1.2.840.10008.1.2.4.91") )
593 * \ingroup gdcmHeader
594 * \brief Predicate for dicom version 3 file.
595 * @return True when the file is a dicom version 3.
597 bool gdcmHeader::IsDicomV3(void) {
598 if ( (filetype == ExplicitVR)
599 || (filetype == ImplicitVR) )
605 * \ingroup gdcmHeader
606 * \brief When the length of an element value is obviously wrong (because
607 * the parser went Jabberwocky) one can hope improving things by
608 * applying this heuristic.
610 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
611 if ( FoundLength == 0xffffffff)
613 ElVal->SetLength(FoundLength);
617 * \ingroup gdcmHeader
622 guint32 gdcmHeader::FindLengthOB(void) {
623 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
626 long PositionOnEntry = ftell(fp);
627 bool FoundSequenceDelimiter = false;
628 guint32 TotalLength = 0;
631 while ( ! FoundSequenceDelimiter) {
639 TotalLength += 4; // We even have to decount the group and element
641 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
642 char msg[100]; // for sprintf. Sorry
643 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
644 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
649 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
650 FoundSequenceDelimiter = true;
651 else if ( n != 0xe000 ){
652 char msg[100]; // for sprintf. Sorry
653 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
655 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
659 ItemLength = ReadInt32();
660 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
661 // the ItemLength with ReadInt32
663 SkipBytes(ItemLength);
665 fseek(fp, PositionOnEntry, SEEK_SET);
670 * \ingroup gdcmHeader
675 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
676 guint16 element = ElVal->GetElement();
677 guint16 group = ElVal->GetGroup();
678 std::string vr = ElVal->GetVR();
680 if( (element == 0x0010) && (group == 0x7fe0) ) {
682 dbg.Verbose(2, "gdcmHeader::FindLength: ",
683 "we reached 7fe0 0010");
686 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
687 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
689 // The following reserved two bytes (see PS 3.5-2001, section
690 // 7.1.2 Data element structure with explicit vr p27) must be
691 // skipped before proceeding on reading the length on 4 bytes.
692 fseek(fp, 2L, SEEK_CUR);
694 guint32 length32 = ReadInt32();
695 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
696 ElVal->SetLength(FindLengthOB());
699 FixFoundLength(ElVal, length32);
703 // Length is encoded on 2 bytes.
704 length16 = ReadInt16();
706 // We can tell the current file is encoded in big endian (like
707 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
708 // and it's value is the one of the encoding of a big endian file.
709 // In order to deal with such big endian encoded files, we have
710 // (at least) two strategies:
711 // * when we load the "Transfer Syntax" tag with value of big endian
712 // encoding, we raise the proper flags. Then we wait for the end
713 // of the META group (0x0002) among which is "Transfer Syntax",
714 // before switching the swap code to big endian. We have to postpone
715 // the switching of the swap code since the META group is fully encoded
716 // in little endian, and big endian coding only starts at the next
717 // group. The corresponding code can be hard to analyse and adds
718 // many additional unnecessary tests for regular tags.
719 // * the second strategy consists in waiting for trouble, that shall
720 // appear when we find the first group with big endian encoding. This
721 // is easy to detect since the length of a "Group Length" tag (the
722 // ones with zero as element number) has to be of 4 (0x0004). When we
723 // encouter 1024 (0x0400) chances are the encoding changed and we
724 // found a group with big endian encoding.
725 // We shall use this second strategy. In order to make sure that we
726 // can interpret the presence of an apparently big endian encoded
727 // length of a "Group Length" without committing a big mistake, we
728 // add an additional check: we look in the already parsed elements
729 // for the presence of a "Transfer Syntax" whose value has to be "big
730 // endian encoding". When this is the case, chances are we have got our
731 // hands on a big endian encoded file: we switch the swap code to
732 // big endian and proceed...
733 if ( (element == 0x0000) && (length16 == 0x0400) ) {
734 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
735 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
740 SwitchSwapToBigEndian();
741 // Restore the unproperly loaded values i.e. the group, the element
742 // and the dictionary entry depending on them.
743 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
744 guint16 CorrectElem = SwapShort(ElVal->GetElement());
745 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
748 // This correct tag is not in the dictionary. Create a new one.
749 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
751 // FIXME this can create a memory leaks on the old entry that be
752 // left unreferenced.
753 ElVal->SetDictEntry(NewTag);
756 // Heuristic: well some files are really ill-formed.
757 if ( length16 == 0xffff) {
759 dbg.Verbose(0, "gdcmHeader::FindLength",
760 "Erroneous element length fixed.");
762 FixFoundLength(ElVal, (guint32)length16);
766 // Either implicit VR or a non DICOM conformal (see not below) explicit
767 // VR that ommited the VR of (at least) this element. Farts happen.
768 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
769 // on Data elements "Implicit and Explicit VR Data Elements shall
770 // not coexist in a Data Set and Data Sets nested within it".]
771 // Length is on 4 bytes.
772 FixFoundLength(ElVal, ReadInt32());
776 * \ingroup gdcmHeader
777 * \brief Swaps back the bytes of 4-byte long integer accordingly to
780 * @return The suggested integer.
782 guint32 gdcmHeader::SwapLong(guint32 a) {
787 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
788 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
792 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
796 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
799 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
806 * \ingroup gdcmHeader
807 * \brief Swaps the bytes so they agree with the processor order
808 * @return The properly swaped 16 bits integer.
810 guint16 gdcmHeader::SwapShort(guint16 a) {
811 if ( (sw==4321) || (sw==2143) )
812 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
817 * \ingroup gdcmHeader
822 void gdcmHeader::SkipBytes(guint32 NBytes) {
823 //FIXME don't dump the returned value
824 (void)fseek(fp, (long)NBytes, SEEK_CUR);
828 * \ingroup gdcmHeader
833 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
834 SkipBytes(ElVal->GetLength());
838 * \ingroup gdcmHeader
843 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
846 if ((guint32)NewSize >= (guint32)0xffffffff) {
847 MaxSizeLoadElementValue = 0xffffffff;
850 MaxSizeLoadElementValue = NewSize;
854 * \ingroup gdcmHeader
855 * \brief Loads the element content if it's length is not bigger
856 * than the value specified with
857 * gdcmHeader::SetMaxSizeLoadElementValue()
859 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
861 guint16 group = ElVal->GetGroup();
862 std::string vr= ElVal->GetVR();
863 guint32 length = ElVal->GetLength();
864 bool SkipLoad = false;
866 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
868 // FIXME Sequences not treated yet !
870 // Ne faudrait-il pas au contraire trouver immediatement
871 // une maniere 'propre' de traiter les sequences (vr = SQ)
872 // car commencer par les ignorer risque de conduire a qq chose
873 // qui pourrait ne pas etre generalisable
874 // Well, I'm expecting your code !!!
879 // Heuristic : a sequence "contains" a set of tags (called items). It looks
880 // like the last tag of a sequence (the one that terminates the sequence)
881 // has a group of 0xfffe (with a dummy length).
883 // Actually (fffe e000) tells us an Element is beginning
884 // (fffe e00d) tells us an Element just ended
885 // (fffe e0dd) tells us the current SEQuence just ended
887 if( group == 0xfffe )
892 ElVal->SetValue("gdcm::Skipped");
896 // When the length is zero things are easy:
902 // The elements whose length is bigger than the specified upper bound
903 // are not loaded. Instead we leave a short notice of the offset of
904 // the element content and it's length.
905 if (length > MaxSizeLoadElementValue) {
906 std::ostringstream s;
907 s << "gdcm::NotLoaded.";
908 s << " Address:" << (long)ElVal->GetOffset();
909 s << " Length:" << ElVal->GetLength();
910 ElVal->SetValue(s.str());
914 // When an integer is expected, read and convert the following two or
915 // four bytes properly i.e. as an integer as opposed to a string.
917 // pour les elements de Value Multiplicity > 1
918 // on aura en fait une serie d'entiers
919 // on devrait pouvoir faire + compact (?)
921 if ( IsAnInteger(ElVal) ) {
923 std::ostringstream s;
925 if (vr == "US" || vr == "SS") {
927 NewInt = ReadInt16();
930 for (int i=1; i < nbInt; i++) {
932 NewInt = ReadInt16();
937 } else if (vr == "UL" || vr == "SL") {
939 NewInt = ReadInt32();
942 for (int i=1; i < nbInt; i++) {
944 NewInt = ReadInt32();
949 ElVal->SetValue(s.str());
953 // We need an additional byte for storing \0 that is not on disk
954 char* NewValue = (char*)malloc(length+1);
956 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
961 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
962 if ( item_read != 1 ) {
964 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
965 ElVal->SetValue("gdcm::UnRead");
968 ElVal->SetValue(NewValue);
973 * \ingroup gdcmHeader
974 * \brief Loads the element while preserving the current
975 * underlying file position indicator as opposed to
976 * to LoadElementValue that modifies it.
977 * @param ElVal Element whose value shall be loaded.
980 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
981 long PositionOnEntry = ftell(fp);
982 LoadElementValue(ElVal);
983 fseek(fp, PositionOnEntry, SEEK_SET);
987 * \ingroup gdcmHeader
988 * \brief Reads a supposed to be 16 Bits integer
989 * \ (swaps it depending on processor endianity)
991 * @return integer acts as a boolean
993 guint16 gdcmHeader::ReadInt16(void) {
996 item_read = fread (&g, (size_t)2,(size_t)1, fp);
997 if ( item_read != 1 ) {
998 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1000 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1002 dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1012 * \ingroup gdcmHeader
1013 * \brief Reads a supposed to be 32 Bits integer
1014 * \ (swaps it depending on processor endianity)
1018 guint32 gdcmHeader::ReadInt32(void) {
1021 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1022 if ( item_read != 1 ) {
1023 //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1025 // dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1027 dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");
1037 * \ingroup gdcmHeader
1042 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1044 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1046 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1047 "failed to Locate gdcmElValue");
1048 return (gdcmElValue*)0;
1054 * \ingroup gdcmHeader
1055 * \brief Build a new Element Value from all the low level arguments.
1056 * Check for existence of dictionary entry, and build
1057 * a default one when absent.
1058 * @param Group group of the underlying DictEntry
1059 * @param Elem element of the underlying DictEntry
1061 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1062 // Find out if the tag we encountered is in the dictionaries:
1063 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1065 NewTag = new gdcmDictEntry(Group, Elem);
1067 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1069 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1070 "failed to allocate gdcmElValue");
1071 return (gdcmElValue*)0;
1077 * \ingroup gdcmHeader
1082 * \return integer acts as a boolean
1084 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value,
1085 guint16 Group, guint16 Elem ) {
1087 // TODO : FIXME JPRx
1089 // on (je) cree une Elvalue ne contenant pas de valeur
1090 // on l'ajoute au ElValSet
1091 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1092 // --> devrait pouvoir etre fait + simplement ???
1094 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1095 PubElValSet.Add(nvElValue);
1096 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1102 * \ingroup gdcmHeader
1103 * \brief Modify (or Creates if not found) an element
1104 * @param Value new value
1107 * \return integer acts as a boolean
1110 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1112 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1113 PubElValSet.Add(nvElValue);
1114 std::string v = Value;
1115 PubElValSet.SetElValueByNumber(v, Group, Elem);
1121 * \ingroup gdcmHeader
1122 * \brief Set a new value if the invoked element exists
1126 * \return integer acts as a boolean
1128 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1130 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1131 std::string v = Value;
1132 PubElValSet.SetElValueByNumber(v, Group, Elem);
1138 * \ingroup gdcmHeader
1139 * \brief Checks if a given ElValue (group,number)
1140 * \ exists in the Public ElValSet
1143 * @return integer acts as a boolean
1146 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1147 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1151 * \ingroup gdcmHeader
1152 * \brief Build a new Element Value from all the low level arguments.
1153 * Check for existence of dictionary entry, and build
1154 * a default one when absent.
1155 * @param Name Name of the underlying DictEntry
1157 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1159 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1161 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1163 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1165 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1166 "failed to allocate gdcmElValue");
1167 return (gdcmElValue*)0;
1173 * \ingroup gdcmHeader
1174 * \brief Read the next tag but WITHOUT loading it's value
1175 * @return On succes the newly created ElValue, NULL on failure.
1177 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1180 gdcmElValue * NewElVal;
1186 // We reached the EOF (or an error occured) and header parsing
1187 // has to be considered as finished.
1188 return (gdcmElValue *)0;
1190 NewElVal = NewElValueByNumber(g, n);
1192 FindLength(NewElVal);
1195 return (gdcmElValue *)0;
1197 NewElVal->SetOffset(ftell(fp));
1198 //if ( (g==0x7fe0) && (n==0x0010) )
1203 * \ingroup gdcmHeader
1204 * \brief Apply some heuristics to predict wether the considered
1205 * element value contains/represents an integer or not.
1206 * @param ElVal The element value on which to apply the predicate.
1207 * @return The result of the heuristical predicate.
1209 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1210 guint16 group = ElVal->GetGroup();
1211 guint16 element = ElVal->GetElement();
1212 std::string vr = ElVal->GetVR();
1213 guint32 length = ElVal->GetLength();
1215 // When we have some semantics on the element we just read, and if we
1216 // a priori know we are dealing with an integer, then we shall be
1217 // able to swap it's element value properly.
1218 if ( element == 0 ) { // This is the group length of the group
1222 dbg.Error("gdcmHeader::IsAnInteger",
1223 "Erroneous Group Length element length.");
1226 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1233 * \ingroup gdcmHeader
1234 * \brief Recover the offset (from the beginning of the file) of the pixels.
1236 size_t gdcmHeader::GetPixelOffset(void) {
1237 // If this file complies with the norm we should encounter the
1238 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1239 // the group that contains the pixel data (hence the "Pixel Data"
1240 // is found by indirection through the "Image Location").
1241 // Inside the group pointed by "Image Location" the searched element
1242 // is conventionally the element 0x0010 (when the norm is respected).
1243 // When the "Image Location" is absent we default to group 0x7fe0.
1246 std::string ImageLocation = GetPubElValByName("Image Location");
1247 if ( ImageLocation == GDCM_UNFOUND ) {
1250 grPixel = (guint16) atoi( ImageLocation.c_str() );
1252 if (grPixel != 0x7fe0)
1253 // This is a kludge for old dirty Philips imager.
1258 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1261 return PixelElement->GetOffset();
1267 * \ingroup gdcmHeader
1268 * \brief Searches both the public and the shadow dictionary (when they
1269 * exist) for the presence of the DictEntry with given
1270 * group and element. The public dictionary has precedence on the
1272 * @param group group of the searched DictEntry
1273 * @param element element of the searched DictEntry
1274 * @return Corresponding DictEntry when it exists, NULL otherwise.
1276 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1278 gdcmDictEntry * found = (gdcmDictEntry*)0;
1279 if (!RefPubDict && !RefShaDict) {
1280 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1281 "we SHOULD have a default dictionary");
1284 found = RefPubDict->GetTagByNumber(group, element);
1289 found = RefShaDict->GetTagByNumber(group, element);
1297 * \ingroup gdcmHeader
1298 * \brief Searches both the public and the shadow dictionary (when they
1299 * exist) for the presence of the DictEntry with given name.
1300 * The public dictionary has precedence on the shadow one.
1301 * @param Name name of the searched DictEntry
1302 * @return Corresponding DictEntry when it exists, NULL otherwise.
1304 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1305 gdcmDictEntry * found = (gdcmDictEntry*)0;
1306 if (!RefPubDict && !RefShaDict) {
1307 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1308 "we SHOULD have a default dictionary");
1311 found = RefPubDict->GetTagByName(Name);
1316 found = RefShaDict->GetTagByName(Name);
1324 * \ingroup gdcmHeader
1325 * \brief Searches within the public dictionary for element value of
1327 * @param group Group of the researched tag.
1328 * @param element Element of the researched tag.
1329 * @return Corresponding element value when it exists, and the string
1330 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1332 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1333 return PubElValSet.GetElValueByNumber(group, element);
1337 * \ingroup gdcmHeader
1338 * \brief Searches within the public dictionary for element value
1339 * representation of a given tag.
1341 * Obtaining the VR (Value Representation) might be needed by caller
1342 * to convert the string typed content to caller's native type
1343 * (think of C++ vs Python). The VR is actually of a higher level
1344 * of semantics than just the native C++ type.
1345 * @param group Group of the researched tag.
1346 * @param element Element of the researched tag.
1347 * @return Corresponding element value representation when it exists,
1348 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1350 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1351 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1353 return GDCM_UNFOUND;
1354 return elem->GetVR();
1358 * \ingroup gdcmHeader
1359 * \brief Searches within the public dictionary for element value of
1361 * @param TagName name of the researched element.
1362 * @return Corresponding element value when it exists, and the string
1363 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1365 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1366 return PubElValSet.GetElValueByName(TagName);
1370 * \ingroup gdcmHeader
1371 * \brief Searches within the elements parsed with the public dictionary for
1372 * the element value representation of a given tag.
1374 * Obtaining the VR (Value Representation) might be needed by caller
1375 * to convert the string typed content to caller's native type
1376 * (think of C++ vs Python). The VR is actually of a higher level
1377 * of semantics than just the native C++ type.
1378 * @param TagName name of the researched element.
1379 * @return Corresponding element value representation when it exists,
1380 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1382 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1383 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1385 return GDCM_UNFOUND;
1386 return elem->GetVR();
1390 * \ingroup gdcmHeader
1391 * \brief Searches within elements parsed with the SHADOW dictionary
1392 * for the element value of a given tag.
1393 * @param group Group of the researched tag.
1394 * @param element Element of the researched tag.
1395 * @return Corresponding element value representation when it exists,
1396 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1398 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1399 return ShaElValSet.GetElValueByNumber(group, element);
1403 * \ingroup gdcmHeader
1404 * \brief Searches within the elements parsed with the SHADOW dictionary
1405 * for the element value representation of a given tag.
1407 * Obtaining the VR (Value Representation) might be needed by caller
1408 * to convert the string typed content to caller's native type
1409 * (think of C++ vs Python). The VR is actually of a higher level
1410 * of semantics than just the native C++ type.
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::GetShaElValRepByNumber(guint16 group, guint16 element) {
1417 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1419 return GDCM_UNFOUND;
1420 return elem->GetVR();
1424 * \ingroup gdcmHeader
1425 * \brief Searches within the elements parsed with the shadow dictionary
1426 * for an element value of given tag.
1427 * @param TagName name of the researched element.
1428 * @return Corresponding element value when it exists, and the string
1429 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1431 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1432 return ShaElValSet.GetElValueByName(TagName);
1436 * \ingroup gdcmHeader
1437 * \brief Searches within the elements parsed with the shadow dictionary for
1438 * the element value representation of a given tag.
1440 * Obtaining the VR (Value Representation) might be needed by caller
1441 * to convert the string typed content to caller's native type
1442 * (think of C++ vs Python). The VR is actually of a higher level
1443 * of semantics than just the native C++ type.
1444 * @param TagName name of the researched element.
1445 * @return Corresponding element value representation when it exists,
1446 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1448 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1449 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1451 return GDCM_UNFOUND;
1452 return elem->GetVR();
1456 * \ingroup gdcmHeader
1457 * \brief Searches within elements parsed with the public dictionary
1458 * and then within the elements parsed with the shadow dictionary
1459 * for the element value of a given tag.
1460 * @param group Group of the researched tag.
1461 * @param element Element of the researched tag.
1462 * @return Corresponding element value representation when it exists,
1463 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1465 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1466 std::string pub = GetPubElValByNumber(group, element);
1469 return GetShaElValByNumber(group, element);
1473 * \ingroup gdcmHeader
1474 * \brief Searches within elements parsed with the public dictionary
1475 * and then within the elements parsed with the shadow dictionary
1476 * for the element value representation of a given tag.
1478 * Obtaining the VR (Value Representation) might be needed by caller
1479 * to convert the string typed content to caller's native type
1480 * (think of C++ vs Python). The VR is actually of a higher level
1481 * of semantics than just the native C++ type.
1482 * @param group Group of the researched tag.
1483 * @param element Element of the researched tag.
1484 * @return Corresponding element value representation when it exists,
1485 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1487 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1488 std::string pub = GetPubElValRepByNumber(group, element);
1491 return GetShaElValRepByNumber(group, element);
1495 * \ingroup gdcmHeader
1496 * \brief Searches within elements parsed with the public dictionary
1497 * and then within the elements parsed with the shadow dictionary
1498 * for the element value of a given tag.
1499 * @param TagName name of the researched element.
1500 * @return Corresponding element value when it exists,
1501 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1503 std::string gdcmHeader::GetElValByName(std::string TagName) {
1504 std::string pub = GetPubElValByName(TagName);
1507 return GetShaElValByName(TagName);
1511 * \ingroup gdcmHeader
1512 * \brief Searches within elements parsed with the public dictionary
1513 * and then within the elements parsed with the shadow dictionary
1514 * for the element value representation of a given tag.
1516 * Obtaining the VR (Value Representation) might be needed by caller
1517 * to convert the string typed content to caller's native type
1518 * (think of C++ vs Python). The VR is actually of a higher level
1519 * of semantics than just the native C++ type.
1520 * @param TagName name of the researched element.
1521 * @return Corresponding element value representation when it exists,
1522 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1524 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1525 std::string pub = GetPubElValRepByName(TagName);
1528 return GetShaElValRepByName(TagName);
1532 * \ingroup gdcmHeader
1533 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1534 * through it's (group, element) and modifies it's content with
1536 * @param content new value to substitute with
1537 * @param group group of the ElVal to modify
1538 * @param element element of the ElVal to modify
1540 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1543 //TODO : homogeneiser les noms : SetPubElValByNumber
1544 // qui appelle PubElValSet.SetElValueByNumber
1545 // pourquoi pas SetPubElValueByNumber ??
1548 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1552 * \ingroup gdcmHeader
1553 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1554 * through tag name and modifies it's content with the given value.
1555 * @param content new value to substitute with
1556 * @param TagName name of the tag to be modified
1558 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1559 return ( PubElValSet.SetElValueByName (content, TagName) );
1563 * \ingroup gdcmHeader
1564 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1565 * through it's (group, element) and modifies it's length with
1567 * \warning Use with extreme caution.
1568 * @param length new length to substitute with
1569 * @param group group of the ElVal to modify
1570 * @param element element of the ElVal to modify
1571 * @return 1 on success, 0 otherwise.
1574 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1576 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1580 * \ingroup gdcmHeader
1581 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1582 * through it's (group, element) and modifies it's content with
1584 * @param content new value to substitute with
1585 * @param group group of the ElVal to modify
1586 * @param element element of the ElVal to modify
1587 * @return 1 on success, 0 otherwise.
1589 int gdcmHeader::SetShaElValByNumber(std::string content,
1590 guint16 group, guint16 element) {
1591 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1595 * \ingroup gdcmHeader
1596 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1597 * through tag name and modifies it's content with the given value.
1598 * @param content new value to substitute with
1599 * @param ShadowTagName name of the tag to be modified
1601 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1602 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1606 * \ingroup gdcmHeader
1607 * \brief Parses the header of the file but WITHOUT loading element values.
1609 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1610 gdcmElValue * newElValue = (gdcmElValue *)0;
1614 while ( (newElValue = ReadNextElement()) ) {
1615 SkipElementValue(newElValue);
1616 PubElValSet.Add(newElValue);
1621 * \ingroup gdcmHeader
1622 * \brief This predicate, based on hopefully reasonnable heuristics,
1623 * decides whether or not the current gdcmHeader was properly parsed
1624 * and contains the mandatory information for being considered as
1625 * a well formed and usable image.
1626 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1629 bool gdcmHeader::IsReadable(void) {
1630 if ( GetElValByName("Image Dimensions") != GDCM_UNFOUND
1631 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1634 if ( GetElValByName("Bits Allocated") == GDCM_UNFOUND )
1636 if ( GetElValByName("Bits Stored") == GDCM_UNFOUND )
1638 if ( GetElValByName("High Bit") == GDCM_UNFOUND )
1640 if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1646 * \ingroup gdcmHeader
1647 * \brief Small utility function that creates a new manually crafted
1648 * (as opposed as read from the file) gdcmElValue with user
1649 * specified name and adds it to the public tag hash table.
1650 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1651 * @param NewTagName The name to be given to this new tag.
1652 * @param VR The Value Representation to be given to this new tag.
1653 * @ return The newly hand crafted Element Value.
1655 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName,
1657 gdcmElValue* NewElVal = (gdcmElValue*)0;
1658 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1659 guint32 FreeElem = 0;
1660 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1662 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1663 if (FreeElem == UINT32_MAX) {
1664 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1665 "Group 0xffff in Public Dict is full");
1666 return (gdcmElValue*)0;
1668 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1669 VR, "GDCM", NewTagName);
1670 NewElVal = new gdcmElValue(NewEntry);
1671 PubElValSet.Add(NewElVal);
1676 * \ingroup gdcmHeader
1677 * \brief Loads the element values of all the elements present in the
1678 * public tag based hash table.
1680 void gdcmHeader::LoadElements(void) {
1682 TagElValueHT ht = PubElValSet.GetTagHt();
1683 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1684 LoadElementValue(tag->second);
1688 // Load 'non string' values
1689 std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);
1690 if( PhotometricInterpretation == "PALETTE COLOR " ){
1691 LoadElementVoidArea(0x0028,0x1200); // gray LUT
1692 LoadElementVoidArea(0x0028,0x1201); // R LUT
1693 LoadElementVoidArea(0x0028,0x1202); // G LUT
1694 LoadElementVoidArea(0x0028,0x1203); // B LUT
1696 LoadElementVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1697 LoadElementVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1698 LoadElementVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1701 // --------------------------------------------------------------
1702 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1704 // if recognition code tells us we deal with a LibIDO image
1705 // we switch lineNumber and columnNumber
1707 std::string RecCode;
1708 RecCode = GetPubElValByNumber(0x0008, 0x0010);
1709 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1710 RecCode == "CANRME_AILIBOD1_1." ) {
1711 filetype = ACR_LIBIDO;
1712 std::string rows = GetPubElValByNumber(0x0028, 0x0010);
1713 std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1714 SetPubElValByNumber(columns, 0x0028, 0x0010);
1715 SetPubElValByNumber(rows , 0x0028, 0x0011);
1717 // ----------------- End of Special Patch ----------------
1721 * \ingroup gdcmHeader
1725 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1726 PubElValSet.Print(os);
1730 * \ingroup gdcmHeader
1734 void gdcmHeader::PrintPubDict(std::ostream & os) {
1735 RefPubDict->Print(os);
1739 * \ingroup gdcmHeader
1743 int gdcmHeader::Write(FILE * fp, FileType type) {
1744 return PubElValSet.Write(fp, type);
1748 // ------------------------ 'non string' elements related functions
1752 * \ingroup gdcmHeader
1753 * \brief Loads (from disk) the element content
1754 * when a string is not suitable
1756 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1757 gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1760 size_t o =(size_t)Element->GetOffset();
1761 fseek(fp, o, SEEK_SET);
1762 int l=Element->GetLength();
1763 void * a = malloc(l);
1765 std::cout << "Big Broblem (LoadElementVoidArea, malloc) "
1766 << std::hex << Group << " " << Elem << std::endl;
1769 int res = PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1770 // TODO check the result
1771 size_t l2 = fread(a, 1, l ,fp);
1773 std::cout << "Big Broblem (LoadElementVoidArea, fread) "
1774 << std::hex << Group << " " << Elem << std::endl;
1781 * \ingroup gdcmHeader
1782 * \brief Gets (from Header) the offset of a 'non string' element value
1783 * \ (LoadElementValue has already be executed)
1786 * @return File Offset of the Element Value
1788 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1789 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1791 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1792 "failed to Locate gdcmElValue");
1795 return elValue->GetOffset();
1799 * \ingroup gdcmHeader
1800 * \brief Gets (from Header) a 'non string' element value
1801 * \ (LoadElementValue has already be executed)
1804 * @return Pointer to the 'non string' area
1807 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1808 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1810 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1811 "failed to Locate gdcmElValue");
1814 return elValue->GetVoidArea();
1819 // =============================================================================
1820 // Heuristics based accessors
1821 //==============================================================================
1824 // TODO : move to an other file.
1828 * \ingroup gdcmHeader
1829 * \brief Retrieve the number of columns of image.
1830 * @return The encountered size when found, 0 by default.
1832 int gdcmHeader::GetXSize(void) {
1833 // We cannot check for "Columns" because the "Columns" tag is present
1834 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1835 std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1836 if (StrSize == GDCM_UNFOUND)
1838 return atoi(StrSize.c_str());
1842 * \ingroup gdcmHeader
1843 * \brief Retrieve the number of lines of image.
1844 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1845 * @return The encountered size when found, 1 by default.
1847 int gdcmHeader::GetYSize(void) {
1848 // We cannot check for "Rows" because the "Rows" tag is present
1849 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1850 std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1851 if (StrSize != GDCM_UNFOUND)
1852 return atoi(StrSize.c_str());
1856 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1857 // hence be a signal (1d image). So we default to 1:
1862 * \ingroup gdcmHeader
1863 * \brief Retrieve the number of planes of volume or the number
1864 * of frames of a multiframe.
1865 * \warning When present we consider the "Number of Frames" as the third
1866 * dimension. When absent we consider the third dimension as
1867 * being the "Planes" tag content.
1868 * @return The encountered size when found, 1 by default.
1870 int gdcmHeader::GetZSize(void) {
1871 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1872 // as the third dimension.
1873 std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
1874 if (StrSize != GDCM_UNFOUND)
1875 return atoi(StrSize.c_str());
1877 // We then consider the "Planes" entry as the third dimension [we
1878 // cannot retrieve by name since "Planes tag is present both in
1879 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1880 StrSize = GetPubElValByNumber(0x0028,0x0012);
1881 if (StrSize != GDCM_UNFOUND)
1882 return atoi(StrSize.c_str());
1887 * \ingroup gdcmHeader
1888 * \brief Retrieve the number of Bits Stored
1889 * (as opposite to number of Bits Allocated)
1891 * @return The encountered number of Bits Stored, 0 by default.
1893 int gdcmHeader::GetBitsStored(void) {
1894 std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
1895 if (StrSize == GDCM_UNFOUND)
1897 return atoi(StrSize.c_str());
1902 * \ingroup gdcmHeader
1903 * \brief Retrieve the number of Samples Per Pixel
1904 * (1 : gray level, 3 : RGB)
1906 * @return The encountered number of Samples Per Pixel, 1 by default.
1908 int gdcmHeader::GetSamplesPerPixel(void) {
1909 std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
1910 if (StrSize == GDCM_UNFOUND)
1911 return 1; // Well, it's supposed to be mandatory ...
1912 return atoi(StrSize.c_str());
1916 * \ingroup gdcmHeader
1917 * \brief Retrieve the Planar Configuration for RGB images
1918 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1920 * @return The encountered Planar Configuration, 0 by default.
1922 int gdcmHeader::GetPlanarConfiguration(void) {
1923 std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
1924 if (StrSize == GDCM_UNFOUND)
1926 return atoi(StrSize.c_str());
1930 * \ingroup gdcmHeader
1931 * \brief Return the size (in bytes) of a single pixel of data.
1932 * @return The size in bytes of a single pixel of data.
1935 int gdcmHeader::GetPixelSize(void) {
1936 std::string PixelType = GetPixelType();
1937 if (PixelType == "8U" || PixelType == "8S")
1939 if (PixelType == "16U" || PixelType == "16S")
1941 if (PixelType == "32U" || PixelType == "32S")
1943 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1948 * \ingroup gdcmHeader
1949 * \brief Build the Pixel Type of the image.
1950 * Possible values are:
1951 * - 8U unsigned 8 bit,
1952 * - 8S signed 8 bit,
1953 * - 16U unsigned 16 bit,
1954 * - 16S signed 16 bit,
1955 * - 32U unsigned 32 bit,
1956 * - 32S signed 32 bit,
1957 * \warning 12 bit images appear as 16 bit.
1960 std::string gdcmHeader::GetPixelType(void) {
1961 std::string BitsAlloc;
1962 BitsAlloc = GetElValByName("Bits Allocated");
1963 if (BitsAlloc == GDCM_UNFOUND) {
1964 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1965 BitsAlloc = std::string("16");
1967 if (BitsAlloc == "12")
1968 BitsAlloc = std::string("16");
1971 Signed = GetElValByName("Pixel Representation");
1972 if (Signed == GDCM_UNFOUND) {
1973 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1974 BitsAlloc = std::string("0");
1977 Signed = std::string("U");
1979 Signed = std::string("S");
1981 return( BitsAlloc + Signed);
1985 * \ingroup gdcmHeader
1986 * \brief gets the info from 0002,0010 : Transfert Syntax
1988 * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
1990 std::string gdcmHeader::GetTransferSyntaxName(void) {
1991 std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
1992 if (TransfertSyntax == GDCM_UNFOUND) {
1993 dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
1994 return "Uncompressed ACR-NEMA";
1996 // we do it only when we need it
1997 gdcmTS * ts = gdcmGlobal::GetTS();
1998 std::string tsName=ts->GetValue(TransfertSyntax);
1999 //delete ts; // Seg Fault when deleted ?!
2003 // -------------------------------- Lookup Table related functions ------------
2006 * \ingroup gdcmHeader
2007 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2009 * @return Lookup Table Length
2010 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2013 int gdcmHeader::GetLUTLength(void) {
2014 std::vector<std::string> tokens;
2018 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2019 std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2020 if (LutDescriptionR == GDCM_UNFOUND)
2022 std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2023 if (LutDescriptionG == GDCM_UNFOUND)
2025 std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2026 if (LutDescriptionB == GDCM_UNFOUND)
2028 if( (LutDescriptionR != LutDescriptionG) || (LutDescriptionR != LutDescriptionB) ) {
2029 dbg.Verbose(0, "gdcmHeader::GetLUTLength: The CLUT R,G,B are not equal");
2032 std::cout << "Lut Description " << LutDescriptionR <<std::endl;
2033 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2034 Tokenize (LutDescriptionR, tokens, "\\");
2035 LutLength=atoi(tokens[0].c_str());
2036 //LutDepth=atoi(tokens[1].c_str());
2037 //LutNbits=atoi(tokens[2].c_str());
2043 * \ingroup gdcmHeader
2044 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2046 * @return Lookup Table nBit
2047 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2050 int gdcmHeader::GetLUTNbits(void) {
2051 std::vector<std::string> tokens;
2055 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2056 // Consistency already checked in GetLUTLength
2057 std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2058 if (LutDescription == GDCM_UNFOUND)
2060 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2061 Tokenize (LutDescription, tokens, "\\");
2062 //LutLength=atoi(tokens[0].c_str());
2063 //LutDepth=atoi(tokens[1].c_str());
2064 LutNbits=atoi(tokens[2].c_str());
2071 * \ingroup gdcmHeader
2072 * \brief gets the info from 0028,1201 : Lookup Table Red
2074 * @return Lookup Table Red
2075 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2077 void * gdcmHeader::GetLUTRed(void) {
2078 return GetPubElValVoidAreaByNumber(0x0028,0x1201);
2082 * \ingroup gdcmHeader
2083 * \brief gets the info from 0028,1202 : Lookup Table Green
2085 * @return Lookup Table Red
2086 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2088 void * gdcmHeader::GetLUTGreen(void) {
2089 return GetPubElValVoidAreaByNumber(0x0028,0x1202);
2093 * \ingroup gdcmHeader
2094 * \brief gets the info from 0028,1202 : Lookup Table Blue
2096 * @return Lookup Table Blue
2097 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2099 void * gdcmHeader::GetLUTBlue(void) {
2100 return GetPubElValVoidAreaByNumber(0x0028,0x1203);
2104 * \ingroup gdcmHeader
2106 * @return Lookup Table RGB
2107 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2108 * \ and (0028,1201),(0028,1202),(0028,1202) are found
2109 * \warning : hazardous ! Use better GetPubElValVoidAreaByNumber
2111 void * gdcmHeader::GetLUTRGB(void) {
2112 // Not so easy : see
2113 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2114 // and OT-PAL-8-face.dcm
2116 if (GetPubElValByNumber(0x0028,0x0004) == GDCM_UNFOUND) {
2117 dbg.Verbose(0, "gdcmHeader::GetLUTRGB: unfound Photometric Interpretation");
2120 void * LutR,*LutG,*LutB;
2123 // Maybe, some day we get an image
2124 // that respects the definition ...
2125 // Let's consider no ones does.
2130 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
2172 printf("lut 8 %d : %d %d %d \n",i,*r,*g,*b);
2177 free(LutR); free(LutB); free(LutG);