1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.84 2003/09/18 09:32:15 regrain Exp $
3 //This is needed when compiling in debug mode
5 //'identifier' : not all control paths return a value
6 //#pragma warning ( disable : 4715 )
7 // 'identifier' : class 'type' needs to have dll-interface to be used by
8 // clients of class 'type2'
9 #pragma warning ( disable : 4251 )
10 // 'identifier' : identifier was truncated to 'number' characters in the
12 #pragma warning ( disable : 4786 )
21 #include <netinet/in.h>
23 #include <cctype> // for isalpha
26 #include "gdcmHeader.h"
31 // TODO : remove DEBUG
34 // Refer to gdcmHeader::CheckSwap()
35 #define HEADER_LENGTH_TO_READ 256
36 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
37 //#define _MaxSizeLoadElementValue_ 1024
38 #define _MaxSizeLoadElementValue_ 4096
43 void gdcmHeader::Initialise(void) {
44 dicom_vr = gdcmGlobal::GetVR();
45 dicom_ts = gdcmGlobal::GetTS();
46 Dicts = gdcmGlobal::GetDicts();
47 RefPubDict = Dicts->GetDefaultPubDict();
48 RefShaDict = (gdcmDict*)0;
55 * @param exception_on_error
57 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) {
58 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
59 filename = InFilename;
61 if ( !OpenFile(exception_on_error))
71 * @param exception_on_error
73 gdcmHeader::gdcmHeader(bool exception_on_error) {
74 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
81 * @param exception_on_error
84 bool gdcmHeader::OpenFile(bool exception_on_error)
85 throw(gdcmFileError) {
86 fp=fopen(filename.c_str(),"rb");
87 if(exception_on_error) {
89 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
93 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
100 * @return TRUE if the close was successfull
102 bool gdcmHeader::CloseFile(void) {
103 int closed = fclose(fp);
111 * \ingroup gdcmHeader
112 * \brief Canonical destructor.
114 gdcmHeader::~gdcmHeader (void) {
115 dicom_vr = (gdcmVR*)0;
116 Dicts = (gdcmDictSet*)0;
117 RefPubDict = (gdcmDict*)0;
118 RefShaDict = (gdcmDict*)0;
124 // META Meta Information
136 // NMI Nuclear Medicine
138 // BFS Basic Film Session
139 // BFB Basic Film Box
140 // BIB Basic Image Box
156 * \ingroup gdcmHeader
157 * \brief Discover what the swap code is (among little endian, big endian,
158 * bad little endian, bad big endian).
161 void gdcmHeader::CheckSwap()
163 // The only guaranted way of finding the swap code is to find a
164 // group tag since we know it's length has to be of four bytes i.e.
165 // 0x00000004. Finding the swap code in then straigthforward. Trouble
166 // occurs when we can't find such group...
168 guint32 x=4; // x : for ntohs
169 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
173 char deb[HEADER_LENGTH_TO_READ];
175 // First, compare HostByteOrder and NetworkByteOrder in order to
176 // determine if we shall need to swap bytes (i.e. the Endian type).
182 // The easiest case is the one of a DICOM header, since it possesses a
183 // file preamble where it suffice to look for the string "DICM".
184 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
187 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
188 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
189 // Next, determine the value representation (VR). Let's skip to the
190 // first element (0002, 0000) and check there if we find "UL"
191 // - or "OB" if the 1st one is (0002,0001) -,
192 // in which case we (almost) know it is explicit VR.
193 // WARNING: if it happens to be implicit VR then what we will read
194 // is the length of the group. If this ascii representation of this
195 // length happens to be "UL" then we shall believe it is explicit VR.
196 // FIXME: in order to fix the above warning, we could read the next
197 // element value (or a couple of elements values) in order to make
198 // sure we are not commiting a big mistake.
200 // * the 128 bytes of File Preamble (often padded with zeroes),
201 // * the 4 bytes of "DICM" string,
202 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
203 // i.e. a total of 136 bytes.
206 // Use gdcmHeader::dicom_vr to test all the possibilities
207 // instead of just checking for UL, OB and UI !?
208 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
209 (memcmp(entCur, "OB", (size_t)2) == 0) ||
210 (memcmp(entCur, "UI", (size_t)2) == 0) )
212 filetype = ExplicitVR;
213 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
214 "explicit Value Representation");
216 filetype = ImplicitVR;
217 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
218 "not an explicit Value Representation");
222 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
223 "HostByteOrder != NetworkByteOrder");
226 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
227 "HostByteOrder = NetworkByteOrder");
230 // Position the file position indicator at first tag (i.e.
231 // after the file preamble and the "DICM" string).
233 fseek (fp, 132L, SEEK_SET);
237 // Alas, this is not a DicomV3 file and whatever happens there is no file
238 // preamble. We can reset the file position indicator to where the data
239 // is (i.e. the beginning of the file).
240 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
243 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
244 // By clean we mean that the length of the first tag is written down.
245 // If this is the case and since the length of the first group HAS to be
246 // four (bytes), then determining the proper swap code is straightforward.
249 // We assume the array of char we are considering contains the binary
250 // representation of a 32 bits integer. Hence the following dirty
252 s = *((guint32 *)(entCur));
272 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
273 "ACR/NEMA unfound swap info (time to raise bets)");
276 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
277 // It is time for despaired wild guesses. So, let's assume this file
278 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
279 // not present. Then the only info we have is the net2host one.
289 * \ingroup gdcmHeader
292 void gdcmHeader::SwitchSwapToBigEndian(void) {
293 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
294 "Switching to BigEndian mode.");
312 * \ingroup gdcmHeader
313 * \brief Find the value representation of the current tag.
316 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
317 if (filetype != ExplicitVR)
323 char msg[100]; // for sprintf. Sorry
325 long PositionOnEntry = ftell(fp);
326 // Warning: we believe this is explicit VR (Value Representation) because
327 // we used a heuristic that found "UL" in the first tag. Alas this
328 // doesn't guarantee that all the tags will be in explicit VR. In some
329 // cases (see e-film filtered files) one finds implicit VR tags mixed
330 // within an explicit VR file. Hence we make sure the present tag
331 // is in explicit VR and try to fix things if it happens not to be
333 bool RealExplicit = true;
335 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
339 // Assume we are reading a falsely explicit VR file i.e. we reached
340 // a tag where we expect reading a VR but are in fact we read the
341 // first to bytes of the length. Then we will interogate (through find)
342 // the dicom_vr dictionary with oddities like "\004\0" which crashes
343 // both GCC and VC++ implementations of the STL map. Hence when the
344 // expected VR read happens to be non-ascii characters we consider
345 // we hit falsely explicit VR tag.
347 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
348 RealExplicit = false;
350 // CLEANME searching the dicom_vr at each occurence is expensive.
351 // PostPone this test in an optional integrity check at the end
352 // of parsing or only in debug mode.
353 if ( RealExplicit && !dicom_vr->Count(vr) )
356 if ( RealExplicit ) {
357 if ( ElVal->IsVrUnknown() ) {
358 // When not a dictionary entry, we can safely overwrite the vr.
362 if ( ElVal->GetVR() == vr ) {
363 // The vr we just read and the dictionary agree. Nothing to do.
366 // The vr present in the file and the dictionary disagree. We assume
367 // the file writer knew best and use the vr of the file. Since it would
368 // be unwise to overwrite the vr of a dictionary (since it would
369 // compromise it's next user), we need to clone the actual DictEntry
370 // and change the vr for the read one.
371 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
376 ElVal->SetDictEntry(NewTag);
380 // We thought this was explicit VR, but we end up with an
381 // implicit VR tag. Let's backtrack.
383 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", ElVal->GetGroup(),ElVal->GetElement());
384 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
386 fseek(fp, PositionOnEntry, SEEK_SET);
387 // When this element is known in the dictionary we shall use, e.g. for
388 // the semantics (see the usage of IsAnInteger), the vr proposed by the
389 // dictionary entry. Still we have to flag the element as implicit since
390 // we know now our assumption on expliciteness is not furfilled.
392 if ( ElVal->IsVrUnknown() )
393 ElVal->SetVR("Implicit");
394 ElVal->SetImplicitVr();
398 * \ingroup gdcmHeader
399 * \brief Determines if the Transfer Syntax was already encountered
400 * and if it corresponds to a ImplicitVRLittleEndian one.
402 * @return True when ImplicitVRLittleEndian found. False in all other cases.
404 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
405 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
408 LoadElementValueSafe(Element);
409 string Transfer = Element->GetValue();
410 if ( Transfer == "1.2.840.10008.1.2" )
416 * \ingroup gdcmHeader
417 * \brief Determines if the Transfer Syntax was already encountered
418 * and if it corresponds to a ExplicitVRLittleEndian one.
420 * @return True when ExplicitVRLittleEndian found. False in all other cases.
422 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
423 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
426 LoadElementValueSafe(Element);
427 string Transfer = Element->GetValue();
428 if ( Transfer == "1.2.840.10008.1.2.1" )
434 * \ingroup gdcmHeader
435 * \brief Determines if the Transfer Syntax was already encountered
436 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
438 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
440 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
441 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
444 LoadElementValueSafe(Element);
445 string Transfer = Element->GetValue();
446 if ( Transfer == "1.2.840.10008.1.2.1.99" )
452 * \ingroup gdcmHeader
453 * \brief Determines if the Transfer Syntax was already encountered
454 * and if it corresponds to a Explicit VR Big Endian one.
456 * @return True when big endian found. False in all other cases.
458 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
459 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
462 LoadElementValueSafe(Element);
463 string Transfer = Element->GetValue();
464 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
470 * \ingroup gdcmHeader
471 * \brief Determines if the Transfer Syntax was already encountered
472 * and if it corresponds to a JPEGBaseLineProcess1 one.
474 * @return True when JPEGBaseLineProcess1found. False in all other cases.
476 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
477 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
480 LoadElementValueSafe(Element);
481 string Transfer = Element->GetValue();
482 if ( Transfer == "1.2.840.10008.1.2.4.50" )
488 * \ingroup gdcmHeader
493 bool gdcmHeader::IsJPEGLossless(void) {
494 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
495 // faire qq chose d'intelligent a la place de ça
498 LoadElementValueSafe(Element);
499 const char * Transfert = Element->GetValue().c_str();
500 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
501 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
507 * \ingroup gdcmHeader
508 * \brief Determines if the Transfer Syntax was already encountered
509 * and if it corresponds to a JPEGExtendedProcess2-4 one.
511 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
513 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
514 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
517 LoadElementValueSafe(Element);
518 string Transfer = Element->GetValue();
519 if ( Transfer == "1.2.840.10008.1.2.4.51" )
525 * \ingroup gdcmHeader
526 * \brief Determines if the Transfer Syntax was already encountered
527 * and if it corresponds to a JPEGExtendeProcess3-5 one.
529 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
531 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
532 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
535 LoadElementValueSafe(Element);
536 string Transfer = Element->GetValue();
537 if ( Transfer == "1.2.840.10008.1.2.4.52" )
543 * \ingroup gdcmHeader
544 * \brief Determines if the Transfer Syntax was already encountered
545 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
547 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
550 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
551 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
554 LoadElementValueSafe(Element);
555 string Transfer = Element->GetValue();
556 if ( Transfer == "1.2.840.10008.1.2.4.53" )
562 * \ingroup gdcmHeader
563 * \brief Determines if the Transfer Syntax was already encountered
564 * and if it corresponds to a RLE Lossless one.
566 * @return True when RLE Lossless found. False in all
569 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
570 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
573 LoadElementValueSafe(Element);
574 string Transfer = Element->GetValue();
575 if ( Transfer == "1.2.840.10008.1.2.5" )
581 * \ingroup gdcmHeader
582 * \brief Determines if the Transfer Syntax was already encountered
583 * and if it corresponds to a JPEG200 one.0
585 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
588 bool gdcmHeader::IsJPEG2000(void) {
589 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
592 LoadElementValueSafe(Element);
593 string Transfer = Element->GetValue();
594 if ( (Transfer == "1.2.840.10008.1.2.4.90")
595 || (Transfer == "1.2.840.10008.1.2.4.91") )
601 * \ingroup gdcmHeader
602 * \brief Predicate for dicom version 3 file.
603 * @return True when the file is a dicom version 3.
605 bool gdcmHeader::IsDicomV3(void) {
606 if ( (filetype == ExplicitVR)
607 || (filetype == ImplicitVR) )
613 * \ingroup gdcmHeader
614 * \brief When the length of an element value is obviously wrong (because
615 * the parser went Jabberwocky) one can hope improving things by
616 * applying this heuristic.
618 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
619 if ( FoundLength == 0xffffffff)
621 ElVal->SetLength(FoundLength);
625 * \ingroup gdcmHeader
630 guint32 gdcmHeader::FindLengthOB(void) {
631 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
634 long PositionOnEntry = ftell(fp);
635 bool FoundSequenceDelimiter = false;
636 guint32 TotalLength = 0;
639 while ( ! FoundSequenceDelimiter) {
647 TotalLength += 4; // We even have to decount the group and element
649 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
650 char msg[100]; // for sprintf. Sorry
651 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
652 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
657 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
658 FoundSequenceDelimiter = true;
659 else if ( n != 0xe000 ){
660 char msg[100]; // for sprintf. Sorry
661 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
662 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
666 ItemLength = ReadInt32();
667 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
668 // the ItemLength with ReadInt32
670 SkipBytes(ItemLength);
672 fseek(fp, PositionOnEntry, SEEK_SET);
677 * \ingroup gdcmHeader
682 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
683 guint16 element = ElVal->GetElement();
684 guint16 group = ElVal->GetGroup();
685 string vr = ElVal->GetVR();
687 if( (element == 0x0010) && (group == 0x7fe0) ) {
689 dbg.Verbose(2, "gdcmHeader::FindLength: ",
690 "on est sur 7fe0 0010");
693 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
694 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
696 // The following reserved two bytes (see PS 3.5-2001, section
697 // 7.1.2 Data element structure with explicit vr p27) must be
698 // skipped before proceeding on reading the length on 4 bytes.
699 fseek(fp, 2L, SEEK_CUR);
701 guint32 length32 = ReadInt32();
702 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
703 ElVal->SetLength(FindLengthOB());
706 FixFoundLength(ElVal, length32);
710 // Length is encoded on 2 bytes.
711 length16 = ReadInt16();
713 // We can tell the current file is encoded in big endian (like
714 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
715 // and it's value is the one of the encoding of a big endian file.
716 // In order to deal with such big endian encoded files, we have
717 // (at least) two strategies:
718 // * when we load the "Transfer Syntax" tag with value of big endian
719 // encoding, we raise the proper flags. Then we wait for the end
720 // of the META group (0x0002) among which is "Transfer Syntax",
721 // before switching the swap code to big endian. We have to postpone
722 // the switching of the swap code since the META group is fully encoded
723 // in little endian, and big endian coding only starts at the next
724 // group. The corresponding code can be hard to analyse and adds
725 // many additional unnecessary tests for regular tags.
726 // * the second strategy consists in waiting for trouble, that shall
727 // appear when we find the first group with big endian encoding. This
728 // is easy to detect since the length of a "Group Length" tag (the
729 // ones with zero as element number) has to be of 4 (0x0004). When we
730 // encouter 1024 (0x0400) chances are the encoding changed and we
731 // found a group with big endian encoding.
732 // We shall use this second strategy. In order to make sure that we
733 // can interpret the presence of an apparently big endian encoded
734 // length of a "Group Length" without committing a big mistake, we
735 // add an additional check: we look in the already parsed elements
736 // for the presence of a "Transfer Syntax" whose value has to be "big
737 // endian encoding". When this is the case, chances are we have got our
738 // hands on a big endian encoded file: we switch the swap code to
739 // big endian and proceed...
740 if ( (element == 0x0000) && (length16 == 0x0400) ) {
741 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
742 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
747 SwitchSwapToBigEndian();
748 // Restore the unproperly loaded values i.e. the group, the element
749 // and the dictionary entry depending on them.
750 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
751 guint16 CorrectElem = SwapShort(ElVal->GetElement());
752 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
755 // This correct tag is not in the dictionary. Create a new one.
756 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
758 // FIXME this can create a memory leaks on the old entry that be
759 // left unreferenced.
760 ElVal->SetDictEntry(NewTag);
763 // Heuristic: well some files are really ill-formed.
764 if ( length16 == 0xffff) {
766 dbg.Verbose(0, "gdcmHeader::FindLength",
767 "Erroneous element length fixed.");
769 FixFoundLength(ElVal, (guint32)length16);
773 // Either implicit VR or a non DICOM conformal (see not below) explicit
774 // VR that ommited the VR of (at least) this element. Farts happen.
775 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
776 // on Data elements "Implicit and Explicit VR Data Elements shall
777 // not coexist in a Data Set and Data Sets nested within it".]
778 // Length is on 4 bytes.
779 FixFoundLength(ElVal, ReadInt32());
783 * \ingroup gdcmHeader
784 * \brief Swaps back the bytes of 4-byte long integer accordingly to
787 * @return The suggested integer.
789 guint32 gdcmHeader::SwapLong(guint32 a) {
794 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
795 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
799 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
803 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
806 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
813 * \ingroup gdcmHeader
814 * \brief Swaps the bytes so they agree with the processor order
815 * @return The properly swaped 16 bits integer.
817 guint16 gdcmHeader::SwapShort(guint16 a) {
818 if ( (sw==4321) || (sw==2143) )
819 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
824 * \ingroup gdcmHeader
829 void gdcmHeader::SkipBytes(guint32 NBytes) {
830 //FIXME don't dump the returned value
831 (void)fseek(fp, (long)NBytes, SEEK_CUR);
835 * \ingroup gdcmHeader
840 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
841 SkipBytes(ElVal->GetLength());
845 * \ingroup gdcmHeader
850 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
853 if ((guint32)NewSize >= (guint32)0xffffffff) {
854 MaxSizeLoadElementValue = 0xffffffff;
857 MaxSizeLoadElementValue = NewSize;
861 * \ingroup gdcmHeader
862 * \brief Loads the element content if it's length is not bigger
863 * than the value specified with
864 * gdcmHeader::SetMaxSizeLoadElementValue()
866 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
868 guint16 group = ElVal->GetGroup();
869 string vr = ElVal->GetVR();
870 guint32 length = ElVal->GetLength();
871 bool SkipLoad = false;
873 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
875 // FIXME Sequences not treated yet !
877 // Ne faudrait-il pas au contraire trouver immediatement
878 // une maniere 'propre' de traiter les sequences (vr = SQ)
879 // car commencer par les ignorer risque de conduire a qq chose
880 // qui pourrait ne pas etre generalisable
881 // Well, I'm expecting your code !!!
886 // Heuristic : a sequence "contains" a set of tags (called items). It looks
887 // like the last tag of a sequence (the one that terminates the sequence)
888 // has a group of 0xfffe (with a dummy length).
890 // Actually (fffe e000) tells us an Element is beginning
891 // (fffe e00d) tells us an Element just ended
892 // (fffe e0dd) tells us the current SEQuence just ended
894 if( group == 0xfffe )
899 ElVal->SetValue("gdcm::Skipped");
903 // When the length is zero things are easy:
909 // The elements whose length is bigger than the specified upper bound
910 // are not loaded. Instead we leave a short notice of the offset of
911 // the element content and it's length.
912 if (length > MaxSizeLoadElementValue) {
914 s << "gdcm::NotLoaded.";
915 s << " Address:" << (long)ElVal->GetOffset();
916 s << " Length:" << ElVal->GetLength();
917 ElVal->SetValue(s.str());
921 // When an integer is expected, read and convert the following two or
922 // four bytes properly i.e. as an integer as opposed to a string.
924 // pour les elements de Value Multiplicity > 1
925 // on aura en fait une serie d'entiers
926 // on devrait pouvoir faire + compact (?)
928 if ( IsAnInteger(ElVal) ) {
932 if (vr == "US" || vr == "SS") {
934 NewInt = ReadInt16();
937 for (int i=1; i < nbInt; i++) {
939 NewInt = ReadInt16();
944 } else if (vr == "UL" || vr == "SL") {
946 NewInt = ReadInt32();
949 for (int i=1; i < nbInt; i++) {
951 NewInt = ReadInt32();
956 ElVal->SetValue(s.str());
960 // We need an additional byte for storing \0 that is not on disk
961 char* NewValue = (char*)malloc(length+1);
963 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
968 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
969 if ( item_read != 1 ) {
971 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
972 ElVal->SetValue("gdcm::UnRead");
975 ElVal->SetValue(NewValue);
980 * \ingroup gdcmHeader
981 * \brief Loads the element while preserving the current
982 * underlying file position indicator as opposed to
983 * to LoadElementValue that modifies it.
984 * @param ElVal Element whose value shall be loaded.
987 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
988 long PositionOnEntry = ftell(fp);
989 LoadElementValue(ElVal);
990 fseek(fp, PositionOnEntry, SEEK_SET);
994 * \ingroup gdcmHeader
995 * \brief Reads a supposed to be 16 Bits integer
996 * \ (swaps it depending on processor endianity)
998 * @return integer acts as a boolean
1000 guint16 gdcmHeader::ReadInt16(void) {
1003 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1004 if ( item_read != 1 ) {
1005 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1007 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1009 dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1019 * \ingroup gdcmHeader
1020 * \brief Reads a supposed to be 32 Bits integer
1021 * \ (swaps it depending on processor endianity)
1025 guint32 gdcmHeader::ReadInt32(void) {
1028 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1029 if ( item_read != 1 ) {
1030 //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1032 // dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1034 dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");
1044 * \ingroup gdcmHeader
1049 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1051 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1053 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1054 "failed to Locate gdcmElValue");
1055 return (gdcmElValue*)0;
1061 * \ingroup gdcmHeader
1062 * \brief Build a new Element Value from all the low level arguments.
1063 * Check for existence of dictionary entry, and build
1064 * a default one when absent.
1065 * @param Group group of the underlying DictEntry
1066 * @param Elem element of the underlying DictEntry
1068 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1069 // Find out if the tag we encountered is in the dictionaries:
1070 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1072 NewTag = new gdcmDictEntry(Group, Elem);
1074 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1076 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1077 "failed to allocate gdcmElValue");
1078 return (gdcmElValue*)0;
1084 * \ingroup gdcmHeader
1089 * \return integer acts as a boolean
1091 int gdcmHeader::ReplaceOrCreateByNumber(string Value, guint16 Group, guint16 Elem ) {
1093 // TODO : FIXME JPRx
1095 // on (je) cree une Elvalue ne contenant pas de valeur
1096 // on l'ajoute au ElValSet
1097 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1098 // --> devrait pouvoir etre fait + simplement ???
1100 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1101 PubElValSet.Add(nvElValue);
1102 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1108 * \ingroup gdcmHeader
1109 * \brief Modify or (Creates if not found) an element
1110 * @param Value new value
1113 * \return integer acts as a boolean
1116 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1118 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1119 PubElValSet.Add(nvElValue);
1121 PubElValSet.SetElValueByNumber(v, Group, Elem);
1127 * \ingroup gdcmHeader
1128 * \brief Set a new value if the invoked element exists
1132 * \return integer acts as a boolean
1134 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1136 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1138 PubElValSet.SetElValueByNumber(v, Group, Elem);
1144 * \ingroup gdcmHeader
1145 * \brief Checks if a given ElValue (group,number)
1146 * \ exists in the Public ElValSet
1149 * @return integer acts as a boolean
1152 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1153 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1157 * \ingroup gdcmHeader
1158 * \brief Build a new Element Value from all the low level arguments.
1159 * Check for existence of dictionary entry, and build
1160 * a default one when absent.
1161 * @param Name Name of the underlying DictEntry
1163 gdcmElValue* gdcmHeader::NewElValueByName(string Name) {
1165 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1167 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1169 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1171 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1172 "failed to allocate gdcmElValue");
1173 return (gdcmElValue*)0;
1179 * \ingroup gdcmHeader
1180 * \brief Read the next tag but WITHOUT loading it's value
1181 * @return On succes the newly created ElValue, NULL on failure.
1183 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1186 gdcmElValue * NewElVal;
1191 if ( (g==0x7fe0) && (n==0x0010) )
1193 printf("in gdcmHeader::ReadNextElement try to read 7fe0 0010 \n");
1196 // We reached the EOF (or an error occured) and header parsing
1197 // has to be considered as finished.
1198 return (gdcmElValue *)0;
1200 NewElVal = NewElValueByNumber(g, n);
1202 FindLength(NewElVal);
1205 if (DEBUG) printf("in gdcmHeader::ReadNextElement : g %04x n %04x errno %d\n",g, n, errno);
1206 return (gdcmElValue *)0;
1208 NewElVal->SetOffset(ftell(fp));
1209 if ( (g==0x7fe0) && (n==0x0010) )
1211 printf("sortie de gdcmHeader::ReadNextElement 7fe0 0010 \n");
1216 * \ingroup gdcmHeader
1217 * \brief Apply some heuristics to predict wether the considered
1218 * element value contains/represents an integer or not.
1219 * @param ElVal The element value on which to apply the predicate.
1220 * @return The result of the heuristical predicate.
1222 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1223 guint16 group = ElVal->GetGroup();
1224 guint16 element = ElVal->GetElement();
1225 string vr = ElVal->GetVR();
1226 guint32 length = ElVal->GetLength();
1228 // When we have some semantics on the element we just read, and if we
1229 // a priori know we are dealing with an integer, then we shall be
1230 // able to swap it's element value properly.
1231 if ( element == 0 ) { // This is the group length of the group
1235 if (DEBUG) printf("Erroneous Group Length element length (%04x , %04x) : %d\n",
1236 group, element,length);
1238 dbg.Error("gdcmHeader::IsAnInteger",
1239 "Erroneous Group Length element length.");
1242 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1249 * \ingroup gdcmHeader
1250 * \brief Recover the offset (from the beginning of the file) of the pixels.
1252 size_t gdcmHeader::GetPixelOffset(void) {
1253 // If this file complies with the norm we should encounter the
1254 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1255 // the group that contains the pixel data (hence the "Pixel Data"
1256 // is found by indirection through the "Image Location").
1257 // Inside the group pointed by "Image Location" the searched element
1258 // is conventionally the element 0x0010 (when the norm is respected).
1259 // When the "Image Location" is absent we default to group 0x7fe0.
1262 string ImageLocation = GetPubElValByName("Image Location");
1263 if ( ImageLocation == GDCM_UNFOUND ) {
1266 grPixel = (guint16) atoi( ImageLocation.c_str() );
1268 if (grPixel != 0x7fe0)
1269 // This is a kludge for old dirty Philips imager.
1274 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1277 return PixelElement->GetOffset();
1283 * \ingroup gdcmHeader
1284 * \brief Searches both the public and the shadow dictionary (when they
1285 * exist) for the presence of the DictEntry with given
1286 * group and element. The public dictionary has precedence on the
1288 * @param group group of the searched DictEntry
1289 * @param element element of the searched DictEntry
1290 * @return Corresponding DictEntry when it exists, NULL otherwise.
1292 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1294 gdcmDictEntry * found = (gdcmDictEntry*)0;
1295 if (!RefPubDict && !RefShaDict) {
1296 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1297 "we SHOULD have a default dictionary");
1300 found = RefPubDict->GetTagByNumber(group, element);
1305 found = RefShaDict->GetTagByNumber(group, element);
1313 * \ingroup gdcmHeader
1314 * \brief Searches both the public and the shadow dictionary (when they
1315 * exist) for the presence of the DictEntry with given name.
1316 * The public dictionary has precedence on the shadow one.
1317 * @param Name name of the searched DictEntry
1318 * @return Corresponding DictEntry when it exists, NULL otherwise.
1320 gdcmDictEntry * gdcmHeader::GetDictEntryByName(string Name) {
1321 gdcmDictEntry * found = (gdcmDictEntry*)0;
1322 if (!RefPubDict && !RefShaDict) {
1323 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1324 "we SHOULD have a default dictionary");
1327 found = RefPubDict->GetTagByName(Name);
1332 found = RefShaDict->GetTagByName(Name);
1340 * \ingroup gdcmHeader
1341 * \brief Searches within the public dictionary for element value of
1343 * @param group Group of the researched tag.
1344 * @param element Element of the researched tag.
1345 * @return Corresponding element value when it exists, and the string
1346 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1348 string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1349 return PubElValSet.GetElValueByNumber(group, element);
1353 * \ingroup gdcmHeader
1354 * \brief Searches within the public dictionary for element value
1355 * representation of a given tag.
1357 * Obtaining the VR (Value Representation) might be needed by caller
1358 * to convert the string typed content to caller's native type
1359 * (think of C++ vs Python). The VR is actually of a higher level
1360 * of semantics than just the native C++ type.
1361 * @param group Group of the researched tag.
1362 * @param element Element of the researched tag.
1363 * @return Corresponding element value representation when it exists,
1364 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1366 string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1367 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1369 return GDCM_UNFOUND;
1370 return elem->GetVR();
1374 * \ingroup gdcmHeader
1375 * \brief Searches within the public dictionary for element value of
1377 * @param TagName name of the researched element.
1378 * @return Corresponding element value when it exists, and the string
1379 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1381 string gdcmHeader::GetPubElValByName(string TagName) {
1382 return PubElValSet.GetElValueByName(TagName);
1386 * \ingroup gdcmHeader
1387 * \brief Searches within the elements parsed with the public dictionary for
1388 * the element value representation of a given tag.
1390 * Obtaining the VR (Value Representation) might be needed by caller
1391 * to convert the string typed content to caller's native type
1392 * (think of C++ vs Python). The VR is actually of a higher level
1393 * of semantics than just the native C++ type.
1394 * @param TagName name of the researched element.
1395 * @return Corresponding element value representation when it exists,
1396 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1398 string gdcmHeader::GetPubElValRepByName(string TagName) {
1399 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1401 return GDCM_UNFOUND;
1402 return elem->GetVR();
1406 * \ingroup gdcmHeader
1407 * \brief Searches within elements parsed with the SHADOW dictionary
1408 * for the element value of a given tag.
1409 * @param group Group of the researched tag.
1410 * @param element Element of the researched tag.
1411 * @return Corresponding element value representation when it exists,
1412 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1414 string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1415 return ShaElValSet.GetElValueByNumber(group, element);
1419 * \ingroup gdcmHeader
1420 * \brief Searches within the elements parsed with the SHADOW dictionary
1421 * for the element value representation of a given tag.
1423 * Obtaining the VR (Value Representation) might be needed by caller
1424 * to convert the string typed content to caller's native type
1425 * (think of C++ vs Python). The VR is actually of a higher level
1426 * of semantics than just the native C++ type.
1427 * @param group Group of the researched tag.
1428 * @param element Element of the researched tag.
1429 * @return Corresponding element value representation when it exists,
1430 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1432 string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1433 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1435 return GDCM_UNFOUND;
1436 return elem->GetVR();
1440 * \ingroup gdcmHeader
1441 * \brief Searches within the elements parsed with the shadow dictionary
1442 * for an element value of given tag.
1443 * @param TagName name of the researched element.
1444 * @return Corresponding element value when it exists, and the string
1445 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1447 string gdcmHeader::GetShaElValByName(string TagName) {
1448 return ShaElValSet.GetElValueByName(TagName);
1452 * \ingroup gdcmHeader
1453 * \brief Searches within the elements parsed with the shadow dictionary for
1454 * the element value representation of a given tag.
1456 * Obtaining the VR (Value Representation) might be needed by caller
1457 * to convert the string typed content to caller's native type
1458 * (think of C++ vs Python). The VR is actually of a higher level
1459 * of semantics than just the native C++ type.
1460 * @param TagName name of the researched element.
1461 * @return Corresponding element value representation when it exists,
1462 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1464 string gdcmHeader::GetShaElValRepByName(string TagName) {
1465 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1467 return GDCM_UNFOUND;
1468 return elem->GetVR();
1472 * \ingroup gdcmHeader
1473 * \brief Searches within elements parsed with the public dictionary
1474 * and then within the elements parsed with the shadow dictionary
1475 * for the element value of a given tag.
1476 * @param group Group of the researched tag.
1477 * @param element Element of the researched tag.
1478 * @return Corresponding element value representation when it exists,
1479 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1481 string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1482 string pub = GetPubElValByNumber(group, element);
1485 return GetShaElValByNumber(group, element);
1489 * \ingroup gdcmHeader
1490 * \brief Searches within elements parsed with the public dictionary
1491 * and then within the elements parsed with the shadow dictionary
1492 * for the element value representation of a given tag.
1494 * Obtaining the VR (Value Representation) might be needed by caller
1495 * to convert the string typed content to caller's native type
1496 * (think of C++ vs Python). The VR is actually of a higher level
1497 * of semantics than just the native C++ type.
1498 * @param group Group of the researched tag.
1499 * @param element Element of the researched tag.
1500 * @return Corresponding element value representation when it exists,
1501 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1503 string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1504 string pub = GetPubElValRepByNumber(group, element);
1507 return GetShaElValRepByNumber(group, element);
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 of a given tag.
1515 * @param TagName name of the researched element.
1516 * @return Corresponding element value when it exists,
1517 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1519 string gdcmHeader::GetElValByName(string TagName) {
1520 string pub = GetPubElValByName(TagName);
1523 return GetShaElValByName(TagName);
1527 * \ingroup gdcmHeader
1528 * \brief Searches within elements parsed with the public dictionary
1529 * and then within the elements parsed with the shadow dictionary
1530 * for the element value representation of a given tag.
1532 * Obtaining the VR (Value Representation) might be needed by caller
1533 * to convert the string typed content to caller's native type
1534 * (think of C++ vs Python). The VR is actually of a higher level
1535 * of semantics than just the native C++ type.
1536 * @param TagName name of the researched element.
1537 * @return Corresponding element value representation when it exists,
1538 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1540 string gdcmHeader::GetElValRepByName(string TagName) {
1541 string pub = GetPubElValRepByName(TagName);
1544 return GetShaElValRepByName(TagName);
1548 * \ingroup gdcmHeader
1549 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1550 * through it's (group, element) and modifies it's content with
1552 * @param content new value to substitute with
1553 * @param group group of the ElVal to modify
1554 * @param element element of the ElVal to modify
1556 int gdcmHeader::SetPubElValByNumber(string content, guint16 group,
1559 //TODO : homogeneiser les noms : SetPubElValByNumber qui appelle PubElValSet.SetElValueByNumber
1560 // pourquoi pas SetPubElValueByNumber ??
1563 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1567 * \ingroup gdcmHeader
1568 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1569 * through tag name and modifies it's content with the given value.
1570 * @param content new value to substitute with
1571 * @param TagName name of the tag to be modified
1573 int gdcmHeader::SetPubElValByName(string content, string TagName) {
1574 return ( PubElValSet.SetElValueByName (content, TagName) );
1578 * \ingroup gdcmHeader
1579 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1580 * through it's (group, element) and modifies it's length with
1582 * \warning Use with extreme caution.
1583 * @param length new length to substitute with
1584 * @param group group of the ElVal to modify
1585 * @param element element of the ElVal to modify
1586 * @return 1 on success, 0 otherwise.
1589 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1591 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1595 * \ingroup gdcmHeader
1596 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1597 * through it's (group, element) and modifies it's content with
1599 * @param content new value to substitute with
1600 * @param group group of the ElVal to modify
1601 * @param element element of the ElVal to modify
1602 * @return 1 on success, 0 otherwise.
1604 int gdcmHeader::SetShaElValByNumber(string content,
1605 guint16 group, guint16 element) {
1606 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1610 * \ingroup gdcmHeader
1611 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1612 * through tag name and modifies it's content with the given value.
1613 * @param content new value to substitute with
1614 * @param ShadowTagName name of the tag to be modified
1616 int gdcmHeader::SetShaElValByName(string content, string ShadowTagName) {
1617 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1621 * \ingroup gdcmHeader
1622 * \brief Parses the header of the file but WITHOUT loading element values.
1624 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1625 gdcmElValue * newElValue = (gdcmElValue *)0;
1629 while ( (newElValue = ReadNextElement()) ) {
1630 SkipElementValue(newElValue);
1631 PubElValSet.Add(newElValue);
1636 * \ingroup gdcmHeader
1637 * \brief This predicate, based on hopefully reasonnable heuristics,
1638 * decides whether or not the current gdcmHeader was properly parsed
1639 * and contains the mandatory information for being considered as
1640 * a well formed and usable image.
1641 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1644 bool gdcmHeader::IsReadable(void) {
1645 if ( GetElValByName("Image Dimensions") != GDCM_UNFOUND
1646 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1649 if ( GetElValByName("Bits Allocated") == GDCM_UNFOUND )
1651 if ( GetElValByName("Bits Stored") == GDCM_UNFOUND )
1653 if ( GetElValByName("High Bit") == GDCM_UNFOUND )
1655 if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1661 * \ingroup gdcmHeader
1662 * \brief Small utility function that creates a new manually crafted
1663 * (as opposed as read from the file) gdcmElValue with user
1664 * specified name and adds it to the public tag hash table.
1665 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1666 * @param NewTagName The name to be given to this new tag.
1667 * @param VR The Value Representation to be given to this new tag.
1668 * @ return The newly hand crafted Element Value.
1670 gdcmElValue* gdcmHeader::NewManualElValToPubDict(string NewTagName, string VR) {
1671 gdcmElValue* NewElVal = (gdcmElValue*)0;
1672 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1673 guint32 FreeElem = 0;
1674 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1676 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1677 if (FreeElem == UINT32_MAX) {
1678 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1679 "Group 0xffff in Public Dict is full");
1680 return (gdcmElValue*)0;
1682 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1683 VR, "GDCM", NewTagName);
1684 NewElVal = new gdcmElValue(NewEntry);
1685 PubElValSet.Add(NewElVal);
1690 * \ingroup gdcmHeader
1691 * \brief Loads the element values of all the elements present in the
1692 * public tag based hash table.
1694 void gdcmHeader::LoadElements(void) {
1696 TagElValueHT ht = PubElValSet.GetTagHt();
1697 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1698 LoadElementValue(tag->second);
1702 // Load 'non string' values
1703 string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);
1704 if( PhotometricInterpretation == "PALETTE COLOR " ){
1705 LoadElementVoidArea(0x0028,0x1200); // gray LUT
1706 LoadElementVoidArea(0x0028,0x1201); // R LUT
1707 LoadElementVoidArea(0x0028,0x1202); // G LUT
1708 LoadElementVoidArea(0x0028,0x1203); // B LUT
1710 LoadElementVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1711 LoadElementVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1712 LoadElementVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1715 // --------------------------------------------------------------
1716 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1718 // if recognition code tells us we deal with a LibIDO image
1719 // we switch lineNumber and columnNumber
1722 RecCode = GetPubElValByNumber(0x0008, 0x0010);
1723 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1724 RecCode == "CANRME_AILIBOD1_1." ) {
1725 filetype = ACR_LIBIDO;
1726 std::string rows = GetPubElValByNumber(0x0028, 0x0010);
1727 std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1728 SetPubElValByNumber(columns, 0x0028, 0x0010);
1729 SetPubElValByNumber(rows , 0x0028, 0x0011);
1731 // ----------------- End of Special Patch ----------------
1735 * \ingroup gdcmHeader
1739 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1740 PubElValSet.Print(os);
1744 * \ingroup gdcmHeader
1748 void gdcmHeader::PrintPubDict(std::ostream & os) {
1749 RefPubDict->Print(os);
1753 * \ingroup gdcmHeader
1757 int gdcmHeader::Write(FILE * fp, FileType type) {
1758 return PubElValSet.Write(fp, type);
1762 // ------------------------ 'non string' elements related functions
1766 * \ingroup gdcmHeader
1767 * \brief Loads (from disk) the element content
1768 * when a string is not suitable
1770 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1771 gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1774 size_t o =(size_t)Element->GetOffset();
1775 fseek(fp, o, SEEK_SET);
1776 int l=Element->GetLength();
1777 void * a = malloc(l);
1779 cout << "Big Broblem (LoadElementVoidArea, malloc) "
1780 << hex << Group << " " << Elem << "\n";
1783 int res = PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1784 // TODO check the result
1785 size_t l2 = fread(a, 1, l ,fp);
1787 cout << "Big Broblem (LoadElementVoidArea, fread) "
1788 << hex << Group << " " << Elem << "\n";
1795 * \ingroup gdcmHeader
1796 * \brief Gets (from Header) the offset of a 'non string' element value
1797 * \ (LoadElementValue has already be executed)
1800 * @return File Offset of the Element Value
1802 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1803 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1805 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1806 "failed to Locate gdcmElValue");
1809 return elValue->GetOffset();
1813 * \ingroup gdcmHeader
1814 * \brief Gets (from Header) a 'non string' element value
1815 * \ (LoadElementValue has already be executed)
1818 * @return Pointer to the 'non string' area
1821 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1822 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1824 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1825 "failed to Locate gdcmElValue");
1828 return elValue->GetVoidArea();
1833 // =============================================================================
1834 // Heuristics based accessors
1835 //==============================================================================
1838 // TODO : move to an other file.
1842 * \ingroup gdcmHeader
1843 * \brief Retrieve the number of columns of image.
1844 * @return The encountered size when found, 0 by default.
1846 int gdcmHeader::GetXSize(void) {
1847 // We cannot check for "Columns" because the "Columns" tag is present
1848 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1849 string StrSize = GetPubElValByNumber(0x0028,0x0011);
1850 if (StrSize == GDCM_UNFOUND)
1852 return atoi(StrSize.c_str());
1856 * \ingroup gdcmHeader
1857 * \brief Retrieve the number of lines of image.
1858 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1859 * @return The encountered size when found, 1 by default.
1861 int gdcmHeader::GetYSize(void) {
1862 // We cannot check for "Rows" because the "Rows" tag is present
1863 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1864 string StrSize = GetPubElValByNumber(0x0028,0x0010);
1865 if (StrSize != GDCM_UNFOUND)
1866 return atoi(StrSize.c_str());
1870 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1871 // hence be a signal (1d image). So we default to 1:
1876 * \ingroup gdcmHeader
1877 * \brief Retrieve the number of planes of volume or the number
1878 * of frames of a multiframe.
1879 * \warning When present we consider the "Number of Frames" as the third
1880 * dimension. When absent we consider the third dimension as
1881 * being the "Planes" tag content.
1882 * @return The encountered size when found, 1 by default.
1884 int gdcmHeader::GetZSize(void) {
1885 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1886 // as the third dimension.
1887 string StrSize = GetPubElValByNumber(0x0028,0x0008);
1888 if (StrSize != GDCM_UNFOUND)
1889 return atoi(StrSize.c_str());
1891 // We then consider the "Planes" entry as the third dimension [we
1892 // cannot retrieve by name since "Planes tag is present both in
1893 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1894 StrSize = GetPubElValByNumber(0x0028,0x0012);
1895 if (StrSize != GDCM_UNFOUND)
1896 return atoi(StrSize.c_str());
1901 * \ingroup gdcmHeader
1902 * \brief Retrieve the number of Bits Stored
1903 * (as opposite to number of Bits Allocated)
1905 * @return The encountered number of Bits Stored, 0 by default.
1907 int gdcmHeader::GetBitsStored(void) {
1908 string StrSize = GetPubElValByNumber(0x0028,0x0101);
1909 if (StrSize == GDCM_UNFOUND)
1911 return atoi(StrSize.c_str());
1916 * \ingroup gdcmHeader
1917 * \brief Retrieve the number of Samples Per Pixel
1918 * (1 : gray level, 3 : RGB)
1920 * @return The encountered number of Samples Per Pixel, 1 by default.
1922 int gdcmHeader::GetSamplesPerPixel(void) {
1923 string StrSize = GetPubElValByNumber(0x0028,0x0002);
1924 if (StrSize == GDCM_UNFOUND)
1925 return 1; // Well, it's supposed to be mandatory ...
1926 return atoi(StrSize.c_str());
1930 * \ingroup gdcmHeader
1931 * \brief Retrieve the Planar Configuration for RGB images
1932 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1934 * @return The encountered Planar Configuration, 0 by default.
1936 int gdcmHeader::GetPlanarConfiguration(void) {
1937 string StrSize = GetPubElValByNumber(0x0028,0x0006);
1938 if (StrSize == GDCM_UNFOUND)
1940 return atoi(StrSize.c_str());
1944 * \ingroup gdcmHeader
1945 * \brief Return the size (in bytes) of a single pixel of data.
1946 * @return The size in bytes of a single pixel of data.
1949 int gdcmHeader::GetPixelSize(void) {
1950 string PixelType = GetPixelType();
1951 if (PixelType == "8U" || PixelType == "8S")
1953 if (PixelType == "16U" || PixelType == "16S")
1955 if (PixelType == "32U" || PixelType == "32S")
1957 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1962 * \ingroup gdcmHeader
1963 * \brief Build the Pixel Type of the image.
1964 * Possible values are:
1965 * - 8U unsigned 8 bit,
1966 * - 8S signed 8 bit,
1967 * - 16U unsigned 16 bit,
1968 * - 16S signed 16 bit,
1969 * - 32U unsigned 32 bit,
1970 * - 32S signed 32 bit,
1971 * \warning 12 bit images appear as 16 bit.
1974 string gdcmHeader::GetPixelType(void) {
1976 BitsAlloc = GetElValByName("Bits Allocated");
1977 if (BitsAlloc == GDCM_UNFOUND) {
1978 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1979 BitsAlloc = string("16");
1981 if (BitsAlloc == "12")
1982 BitsAlloc = string("16");
1985 Signed = GetElValByName("Pixel Representation");
1986 if (Signed == GDCM_UNFOUND) {
1987 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1988 BitsAlloc = string("0");
1991 Signed = string("U");
1993 Signed = string("S");
1995 return( BitsAlloc + Signed);
1999 * \ingroup gdcmHeader
2000 * \brief gets the info from 0002,0010 : Transfert Syntax
2002 * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
2004 string gdcmHeader::GetTransferSyntaxName(void) {
2005 string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
2006 if (TransfertSyntax == GDCM_UNFOUND) {
2007 dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
2008 return "Uncompressed ACR-NEMA";
2010 // we do it only when we need it
2011 gdcmTS * ts = gdcmGlobal::GetTS();
2012 string tsName=ts->GetValue(TransfertSyntax);
2013 //delete ts; // Seg Fault when deleted ?!
2017 // -------------------------------- Lookup Table related functions ------------
2020 * \ingroup gdcmHeader
2021 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2023 * @return Lookup Table Length
2024 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2027 int gdcmHeader::GetLUTLength(void) {
2028 vector<string> tokens;
2032 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2033 string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2034 if (LutDescriptionR == GDCM_UNFOUND)
2036 string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2037 if (LutDescriptionG == GDCM_UNFOUND)
2039 string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2040 if (LutDescriptionB == GDCM_UNFOUND)
2042 if( (LutDescriptionR != LutDescriptionG) || (LutDescriptionR != LutDescriptionB) ) {
2043 dbg.Verbose(0, "gdcmHeader::GetLUTLength: The CLUT R,G,B are not equal");
2046 cout << "Lut Description " << LutDescriptionR <<"\n";
2047 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2048 Tokenize (LutDescriptionR, tokens, "\\");
2049 LutLength=atoi(tokens[0].c_str());
2050 //LutDepth=atoi(tokens[1].c_str());
2051 //LutNbits=atoi(tokens[2].c_str());
2057 * \ingroup gdcmHeader
2058 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2060 * @return Lookup Table nBit
2061 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2064 int gdcmHeader::GetLUTNbits(void) {
2065 vector<string> tokens;
2069 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2070 // Consistency already checked in GetLUTLength
2071 string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2072 if (LutDescription == GDCM_UNFOUND)
2074 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2075 Tokenize (LutDescription, tokens, "\\");
2076 //LutLength=atoi(tokens[0].c_str());
2077 //LutDepth=atoi(tokens[1].c_str());
2078 LutNbits=atoi(tokens[2].c_str());
2085 * \ingroup gdcmHeader
2086 * \brief gets the info from 0028,1201 : Lookup Table Red
2088 * @return Lookup Table Red
2089 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2091 void * gdcmHeader::GetLUTRed(void) {
2092 return GetPubElValVoidAreaByNumber(0x0028,0x1201);
2096 * \ingroup gdcmHeader
2097 * \brief gets the info from 0028,1202 : Lookup Table Green
2099 * @return Lookup Table Red
2100 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2102 void * gdcmHeader::GetLUTGreen(void) {
2103 return GetPubElValVoidAreaByNumber(0x0028,0x1202);
2107 * \ingroup gdcmHeader
2108 * \brief gets the info from 0028,1202 : Lookup Table Blue
2110 * @return Lookup Table Blue
2111 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2113 void * gdcmHeader::GetLUTBlue(void) {
2114 return GetPubElValVoidAreaByNumber(0x0028,0x1203);
2118 * \ingroup gdcmHeader
2120 * @return Lookup Table RGB
2121 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2122 * \ and (0028,1201),(0028,1202),(0028,1202) are found
2123 * \warning : hazardous ! Use better GetPubElValVoidAreaByNumber
2125 void * gdcmHeader::GetLUTRGB(void) {
2126 // Not so easy : see
2127 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2128 // and OT-PAL-8-face.dcm
2130 if (GetPubElValByNumber(0x0028,0x0004) == GDCM_UNFOUND) {
2131 dbg.Verbose(0, "gdcmHeader::GetLUTRGB: unfound Photometric Interpretation");
2134 void * LutR,*LutG,*LutB;
2137 // Maybe, some day we get an image
2138 // that respects the definition ...
2139 // Let's consider no ones does.
2144 int nBits=GetLUTNbits();
2145 // a virer quand on aura trouve UNE image
2146 // qui correspond VRAIMENT à la definition !
2147 cout << "l " << l << " nBits " << nBits;
2151 LutR =GetPubElValVoidAreaByNumber(0x0028,0x1201);
2152 LutG =GetPubElValVoidAreaByNumber(0x0028,0x1202);
2153 LutB =GetPubElValVoidAreaByNumber(0x0028,0x1203);
2155 // Warning : Any value for nBits as to be considered as 8
2156 // Any value for Length as to be considered as 256
2159 // Just wait before removing the following code
2162 guint16 * LUTRGB, *rgb;
2163 LUTRGB = rgb = (guint16 *) malloc(3*l*sizeof( guint16));
2164 guint16 * r = (guint16 *)LutR;
2165 guint16 * g = (guint16 *)LutG;
2166 guint16 * b = (guint16 *)LutB;
2167 for(int i=0;i<l;i++) {
2175 */ { // we assume it's always 8 Bits
2176 l=256; // we assume ...
2177 unsigned char * LUTRGB, *rgb;
2178 LUTRGB = rgb = (unsigned char *) malloc(3*l*sizeof( char));
2179 unsigned char * r = (unsigned char *)LutR;
2180 unsigned char * g = (unsigned char *)LutG;
2181 unsigned char * b = (unsigned char *)LutB;
2182 for(int i=0;i<l;i++) {
2183 //cout << "lut16 " << i << " : " << *r << " " << *g << " " << *b << "\n";
2184 printf("lut 8 %d : %d %d %d \n",i,*r,*g,*b);
2189 free(LutR); free(LutB); free(LutG);