1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.90 2003/09/24 16:18:32 jpr Exp $
3 //This is needed when compiling in debug mode
5 //'identifier' : not all control paths return a value
6 //#pragma warning ( disable : 4715 )
7 // 'identifier' : class 'type' needs to have dll-interface to be used by
8 // clients of class 'type2'
9 #pragma warning ( disable : 4251 )
10 // 'identifier' : identifier was truncated to 'number' characters in the
12 #pragma warning ( disable : 4786 )
21 #include <netinet/in.h>
23 #include <cctype> // for isalpha
26 #include "gdcmHeader.h"
29 // Refer to gdcmHeader::CheckSwap()
30 #define HEADER_LENGTH_TO_READ 256
31 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
32 //#define _MaxSizeLoadElementValue_ 1024
33 #define _MaxSizeLoadElementValue_ 4096
38 void gdcmHeader::Initialise(void) {
39 dicom_vr = gdcmGlobal::GetVR();
40 dicom_ts = gdcmGlobal::GetTS();
41 Dicts = gdcmGlobal::GetDicts();
42 RefPubDict = Dicts->GetDefaultPubDict();
43 RefShaDict = (gdcmDict*)0;
50 * @param exception_on_error
52 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) {
53 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
54 filename = InFilename;
56 if ( !OpenFile(exception_on_error))
58 printf ("avant ParseHeader\n");
60 printf ("avant LoadElements\n");
69 * @param exception_on_error
71 gdcmHeader::gdcmHeader(bool exception_on_error) {
72 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
79 * @param exception_on_error
82 bool gdcmHeader::OpenFile(bool exception_on_error)
83 throw(gdcmFileError) {
84 fp=fopen(filename.c_str(),"rb");
85 if(exception_on_error) {
87 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
91 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
98 * @return TRUE if the close was successfull
100 bool gdcmHeader::CloseFile(void) {
101 int closed = fclose(fp);
109 * \ingroup gdcmHeader
110 * \brief Canonical destructor.
112 gdcmHeader::~gdcmHeader (void) {
113 dicom_vr = (gdcmVR*)0;
114 Dicts = (gdcmDictSet*)0;
115 RefPubDict = (gdcmDict*)0;
116 RefShaDict = (gdcmDict*)0;
122 // META Meta Information
134 // NMI Nuclear Medicine
136 // BFS Basic Film Session
137 // BFB Basic Film Box
138 // BIB Basic Image Box
154 * \ingroup gdcmHeader
155 * \brief Discover what the swap code is (among little endian, big endian,
156 * bad little endian, bad big endian).
159 void gdcmHeader::CheckSwap()
161 // The only guaranted way of finding the swap code is to find a
162 // group tag since we know it's length has to be of four bytes i.e.
163 // 0x00000004. Finding the swap code in then straigthforward. Trouble
164 // occurs when we can't find such group...
166 guint32 x=4; // x : for ntohs
167 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
171 char deb[HEADER_LENGTH_TO_READ];
173 // First, compare HostByteOrder and NetworkByteOrder in order to
174 // determine if we shall need to swap bytes (i.e. the Endian type).
180 // The easiest case is the one of a DICOM header, since it possesses a
181 // file preamble where it suffice to look for the string "DICM".
182 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
185 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
186 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
187 // Next, determine the value representation (VR). Let's skip to the
188 // first element (0002, 0000) and check there if we find "UL"
189 // - or "OB" if the 1st one is (0002,0001) -,
190 // in which case we (almost) know it is explicit VR.
191 // WARNING: if it happens to be implicit VR then what we will read
192 // is the length of the group. If this ascii representation of this
193 // length happens to be "UL" then we shall believe it is explicit VR.
194 // FIXME: in order to fix the above warning, we could read the next
195 // element value (or a couple of elements values) in order to make
196 // sure we are not commiting a big mistake.
198 // * the 128 bytes of File Preamble (often padded with zeroes),
199 // * the 4 bytes of "DICM" string,
200 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
201 // i.e. a total of 136 bytes.
204 // Use gdcmHeader::dicom_vr to test all the possibilities
205 // instead of just checking for UL, OB and UI !?
206 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
207 (memcmp(entCur, "OB", (size_t)2) == 0) ||
208 (memcmp(entCur, "UI", (size_t)2) == 0) )
210 filetype = ExplicitVR;
211 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
212 "explicit Value Representation");
214 filetype = ImplicitVR;
215 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
216 "not an explicit Value Representation");
220 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
221 "HostByteOrder != NetworkByteOrder");
224 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
225 "HostByteOrder = NetworkByteOrder");
228 // Position the file position indicator at first tag (i.e.
229 // after the file preamble and the "DICM" string).
231 fseek (fp, 132L, SEEK_SET);
235 // Alas, this is not a DicomV3 file and whatever happens there is no file
236 // preamble. We can reset the file position indicator to where the data
237 // is (i.e. the beginning of the file).
238 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
241 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
242 // By clean we mean that the length of the first tag is written down.
243 // If this is the case and since the length of the first group HAS to be
244 // four (bytes), then determining the proper swap code is straightforward.
247 // We assume the array of char we are considering contains the binary
248 // representation of a 32 bits integer. Hence the following dirty
250 s = *((guint32 *)(entCur));
270 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
271 "ACR/NEMA unfound swap info (time to raise bets)");
274 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
275 // It is time for despaired wild guesses. So, let's assume this file
276 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
277 // not present. Then the only info we have is the net2host one.
287 * \ingroup gdcmHeader
290 void gdcmHeader::SwitchSwapToBigEndian(void) {
291 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
292 "Switching to BigEndian mode.");
310 * \ingroup gdcmHeader
311 * \brief Find the value representation of the current tag.
314 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
315 if (filetype != ExplicitVR)
321 char msg[100]; // for sprintf. Sorry
323 long PositionOnEntry = ftell(fp);
324 // Warning: we believe this is explicit VR (Value Representation) because
325 // we used a heuristic that found "UL" in the first tag. Alas this
326 // doesn't guarantee that all the tags will be in explicit VR. In some
327 // cases (see e-film filtered files) one finds implicit VR tags mixed
328 // within an explicit VR file. Hence we make sure the present tag
329 // is in explicit VR and try to fix things if it happens not to be
331 bool RealExplicit = true;
333 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
335 vr = std::string(VR);
337 // Assume we are reading a falsely explicit VR file i.e. we reached
338 // a tag where we expect reading a VR but are in fact we read the
339 // first to bytes of the length. Then we will interogate (through find)
340 // the dicom_vr dictionary with oddities like "\004\0" which crashes
341 // both GCC and VC++ implementations of the STL map. Hence when the
342 // expected VR read happens to be non-ascii characters we consider
343 // we hit falsely explicit VR tag.
345 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
346 RealExplicit = false;
348 // CLEANME searching the dicom_vr at each occurence is expensive.
349 // PostPone this test in an optional integrity check at the end
350 // of parsing or only in debug mode.
351 if ( RealExplicit && !dicom_vr->Count(vr) )
354 if ( RealExplicit ) {
355 if ( ElVal->IsVrUnknown() ) {
356 // When not a dictionary entry, we can safely overwrite the vr.
360 if ( ElVal->GetVR() == vr ) {
361 // The vr we just read and the dictionary agree. Nothing to do.
364 // The vr present in the file and the dictionary disagree. We assume
365 // the file writer knew best and use the vr of the file. Since it would
366 // be unwise to overwrite the vr of a dictionary (since it would
367 // compromise it's next user), we need to clone the actual DictEntry
368 // and change the vr for the read one.
369 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
374 ElVal->SetDictEntry(NewTag);
378 // We thought this was explicit VR, but we end up with an
379 // implicit VR tag. Let's backtrack.
381 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n", ElVal->GetGroup(),ElVal->GetElement());
382 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
384 fseek(fp, PositionOnEntry, SEEK_SET);
385 // When this element is known in the dictionary we shall use, e.g. for
386 // the semantics (see the usage of IsAnInteger), the vr proposed by the
387 // dictionary entry. Still we have to flag the element as implicit since
388 // we know now our assumption on expliciteness is not furfilled.
390 if ( ElVal->IsVrUnknown() )
391 ElVal->SetVR("Implicit");
392 ElVal->SetImplicitVr();
396 * \ingroup gdcmHeader
397 * \brief Determines if the Transfer Syntax was already encountered
398 * and if it corresponds to a ImplicitVRLittleEndian one.
400 * @return True when ImplicitVRLittleEndian found. False in all other cases.
402 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
403 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
406 LoadElementValueSafe(Element);
407 std::string Transfer = Element->GetValue();
408 if ( Transfer == "1.2.840.10008.1.2" )
414 * \ingroup gdcmHeader
415 * \brief Determines if the Transfer Syntax was already encountered
416 * and if it corresponds to a ExplicitVRLittleEndian one.
418 * @return True when ExplicitVRLittleEndian found. False in all other cases.
420 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
421 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
424 LoadElementValueSafe(Element);
425 std::string Transfer = Element->GetValue();
426 if ( Transfer == "1.2.840.10008.1.2.1" )
432 * \ingroup gdcmHeader
433 * \brief Determines if the Transfer Syntax was already encountered
434 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
436 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
438 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
439 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
442 LoadElementValueSafe(Element);
443 std::string Transfer = Element->GetValue();
444 if ( Transfer == "1.2.840.10008.1.2.1.99" )
450 * \ingroup gdcmHeader
451 * \brief Determines if the Transfer Syntax was already encountered
452 * and if it corresponds to a Explicit VR Big Endian one.
454 * @return True when big endian found. False in all other cases.
456 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
457 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
460 LoadElementValueSafe(Element);
461 std::string Transfer = Element->GetValue();
462 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
468 * \ingroup gdcmHeader
469 * \brief Determines if the Transfer Syntax was already encountered
470 * and if it corresponds to a JPEGBaseLineProcess1 one.
472 * @return True when JPEGBaseLineProcess1found. False in all other cases.
474 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
475 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
478 LoadElementValueSafe(Element);
479 std::string Transfer = Element->GetValue();
480 if ( Transfer == "1.2.840.10008.1.2.4.50" )
486 * \ingroup gdcmHeader
491 bool gdcmHeader::IsJPEGLossless(void) {
492 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
493 // faire qq chose d'intelligent a la place de ça
496 LoadElementValueSafe(Element);
497 const char * Transfert = Element->GetValue().c_str();
498 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
499 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
505 * \ingroup gdcmHeader
506 * \brief Determines if the Transfer Syntax was already encountered
507 * and if it corresponds to a JPEGExtendedProcess2-4 one.
509 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
511 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
512 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
515 LoadElementValueSafe(Element);
516 std::string Transfer = Element->GetValue();
517 if ( Transfer == "1.2.840.10008.1.2.4.51" )
523 * \ingroup gdcmHeader
524 * \brief Determines if the Transfer Syntax was already encountered
525 * and if it corresponds to a JPEGExtendeProcess3-5 one.
527 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
529 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
530 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
533 LoadElementValueSafe(Element);
534 std::string Transfer = Element->GetValue();
535 if ( Transfer == "1.2.840.10008.1.2.4.52" )
541 * \ingroup gdcmHeader
542 * \brief Determines if the Transfer Syntax was already encountered
543 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
545 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
548 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
549 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
552 LoadElementValueSafe(Element);
553 std::string Transfer = Element->GetValue();
554 if ( Transfer == "1.2.840.10008.1.2.4.53" )
560 * \ingroup gdcmHeader
561 * \brief Determines if the Transfer Syntax was already encountered
562 * and if it corresponds to a RLE Lossless one.
564 * @return True when RLE Lossless found. False in all
567 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
568 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
571 LoadElementValueSafe(Element);
572 std::string Transfer = Element->GetValue();
573 if ( Transfer == "1.2.840.10008.1.2.5" )
579 * \ingroup gdcmHeader
580 * \brief Determines if the Transfer Syntax was already encountered
581 * and if it corresponds to a JPEG200 one.0
583 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
586 bool gdcmHeader::IsJPEG2000(void) {
587 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
590 LoadElementValueSafe(Element);
591 std::string Transfer = Element->GetValue();
592 if ( (Transfer == "1.2.840.10008.1.2.4.90")
593 || (Transfer == "1.2.840.10008.1.2.4.91") )
599 * \ingroup gdcmHeader
600 * \brief Predicate for dicom version 3 file.
601 * @return True when the file is a dicom version 3.
603 bool gdcmHeader::IsDicomV3(void) {
604 if ( (filetype == ExplicitVR)
605 || (filetype == ImplicitVR) )
611 * \ingroup gdcmHeader
612 * \brief When the length of an element value is obviously wrong (because
613 * the parser went Jabberwocky) one can hope improving things by
614 * applying this heuristic.
616 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
617 if ( FoundLength == 0xffffffff)
619 ElVal->SetLength(FoundLength);
623 * \ingroup gdcmHeader
628 guint32 gdcmHeader::FindLengthOB(void) {
629 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
632 long PositionOnEntry = ftell(fp);
633 bool FoundSequenceDelimiter = false;
634 guint32 TotalLength = 0;
637 while ( ! FoundSequenceDelimiter) {
645 TotalLength += 4; // We even have to decount the group and element
647 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
648 char msg[100]; // for sprintf. Sorry
649 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
650 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
655 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
656 FoundSequenceDelimiter = true;
657 else if ( n != 0xe000 ){
658 char msg[100]; // for sprintf. Sorry
659 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",n, g,n);
660 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
664 ItemLength = ReadInt32();
665 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
666 // the ItemLength with ReadInt32
668 SkipBytes(ItemLength);
670 fseek(fp, PositionOnEntry, SEEK_SET);
675 * \ingroup gdcmHeader
680 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
681 guint16 element = ElVal->GetElement();
682 guint16 group = ElVal->GetGroup();
683 std::string vr = ElVal->GetVR();
685 if( (element == 0x0010) && (group == 0x7fe0) ) {
687 dbg.Verbose(2, "gdcmHeader::FindLength: ",
688 "on est sur 7fe0 0010");
691 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
692 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
694 // The following reserved two bytes (see PS 3.5-2001, section
695 // 7.1.2 Data element structure with explicit vr p27) must be
696 // skipped before proceeding on reading the length on 4 bytes.
697 fseek(fp, 2L, SEEK_CUR);
699 guint32 length32 = ReadInt32();
700 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
701 ElVal->SetLength(FindLengthOB());
704 FixFoundLength(ElVal, length32);
708 // Length is encoded on 2 bytes.
709 length16 = ReadInt16();
711 // We can tell the current file is encoded in big endian (like
712 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
713 // and it's value is the one of the encoding of a big endian file.
714 // In order to deal with such big endian encoded files, we have
715 // (at least) two strategies:
716 // * when we load the "Transfer Syntax" tag with value of big endian
717 // encoding, we raise the proper flags. Then we wait for the end
718 // of the META group (0x0002) among which is "Transfer Syntax",
719 // before switching the swap code to big endian. We have to postpone
720 // the switching of the swap code since the META group is fully encoded
721 // in little endian, and big endian coding only starts at the next
722 // group. The corresponding code can be hard to analyse and adds
723 // many additional unnecessary tests for regular tags.
724 // * the second strategy consists in waiting for trouble, that shall
725 // appear when we find the first group with big endian encoding. This
726 // is easy to detect since the length of a "Group Length" tag (the
727 // ones with zero as element number) has to be of 4 (0x0004). When we
728 // encouter 1024 (0x0400) chances are the encoding changed and we
729 // found a group with big endian encoding.
730 // We shall use this second strategy. In order to make sure that we
731 // can interpret the presence of an apparently big endian encoded
732 // length of a "Group Length" without committing a big mistake, we
733 // add an additional check: we look in the already parsed elements
734 // for the presence of a "Transfer Syntax" whose value has to be "big
735 // endian encoding". When this is the case, chances are we have got our
736 // hands on a big endian encoded file: we switch the swap code to
737 // big endian and proceed...
738 if ( (element == 0x0000) && (length16 == 0x0400) ) {
739 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
740 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
745 SwitchSwapToBigEndian();
746 // Restore the unproperly loaded values i.e. the group, the element
747 // and the dictionary entry depending on them.
748 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
749 guint16 CorrectElem = SwapShort(ElVal->GetElement());
750 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
753 // This correct tag is not in the dictionary. Create a new one.
754 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
756 // FIXME this can create a memory leaks on the old entry that be
757 // left unreferenced.
758 ElVal->SetDictEntry(NewTag);
761 // Heuristic: well some files are really ill-formed.
762 if ( length16 == 0xffff) {
764 dbg.Verbose(0, "gdcmHeader::FindLength",
765 "Erroneous element length fixed.");
767 FixFoundLength(ElVal, (guint32)length16);
771 // Either implicit VR or a non DICOM conformal (see not below) explicit
772 // VR that ommited the VR of (at least) this element. Farts happen.
773 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
774 // on Data elements "Implicit and Explicit VR Data Elements shall
775 // not coexist in a Data Set and Data Sets nested within it".]
776 // Length is on 4 bytes.
777 FixFoundLength(ElVal, ReadInt32());
781 * \ingroup gdcmHeader
782 * \brief Swaps back the bytes of 4-byte long integer accordingly to
785 * @return The suggested integer.
787 guint32 gdcmHeader::SwapLong(guint32 a) {
792 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
793 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
797 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
801 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
804 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
811 * \ingroup gdcmHeader
812 * \brief Swaps the bytes so they agree with the processor order
813 * @return The properly swaped 16 bits integer.
815 guint16 gdcmHeader::SwapShort(guint16 a) {
816 if ( (sw==4321) || (sw==2143) )
817 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
822 * \ingroup gdcmHeader
827 void gdcmHeader::SkipBytes(guint32 NBytes) {
828 //FIXME don't dump the returned value
829 (void)fseek(fp, (long)NBytes, SEEK_CUR);
833 * \ingroup gdcmHeader
838 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
839 SkipBytes(ElVal->GetLength());
843 * \ingroup gdcmHeader
848 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
851 if ((guint32)NewSize >= (guint32)0xffffffff) {
852 MaxSizeLoadElementValue = 0xffffffff;
855 MaxSizeLoadElementValue = NewSize;
859 * \ingroup gdcmHeader
860 * \brief Loads the element content if it's length is not bigger
861 * than the value specified with
862 * gdcmHeader::SetMaxSizeLoadElementValue()
864 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
866 guint16 group = ElVal->GetGroup();
867 std::string vr = ElVal->GetVR();
868 guint32 length = ElVal->GetLength();
869 bool SkipLoad = false;
871 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
873 // FIXME Sequences not treated yet !
875 // Ne faudrait-il pas au contraire trouver immediatement
876 // une maniere 'propre' de traiter les sequences (vr = SQ)
877 // car commencer par les ignorer risque de conduire a qq chose
878 // qui pourrait ne pas etre generalisable
879 // Well, I'm expecting your code !!!
884 // Heuristic : a sequence "contains" a set of tags (called items). It looks
885 // like the last tag of a sequence (the one that terminates the sequence)
886 // has a group of 0xfffe (with a dummy length).
888 // Actually (fffe e000) tells us an Element is beginning
889 // (fffe e00d) tells us an Element just ended
890 // (fffe e0dd) tells us the current SEQuence just ended
892 if( group == 0xfffe )
897 ElVal->SetValue("gdcm::Skipped");
901 // When the length is zero things are easy:
907 // The elements whose length is bigger than the specified upper bound
908 // are not loaded. Instead we leave a short notice of the offset of
909 // the element content and it's length.
910 if (length > MaxSizeLoadElementValue) {
911 std::ostringstream s;
912 s << "gdcm::NotLoaded.";
913 s << " Address:" << (long)ElVal->GetOffset();
914 s << " Length:" << ElVal->GetLength();
915 ElVal->SetValue(s.str());
919 // When an integer is expected, read and convert the following two or
920 // four bytes properly i.e. as an integer as opposed to a string.
922 // pour les elements de Value Multiplicity > 1
923 // on aura en fait une serie d'entiers
924 // on devrait pouvoir faire + compact (?)
926 if ( IsAnInteger(ElVal) ) {
928 std::ostringstream s;
930 if (vr == "US" || vr == "SS") {
932 NewInt = ReadInt16();
935 for (int i=1; i < nbInt; i++) {
937 NewInt = ReadInt16();
942 } else if (vr == "UL" || vr == "SL") {
944 NewInt = ReadInt32();
947 for (int i=1; i < nbInt; i++) {
949 NewInt = ReadInt32();
954 ElVal->SetValue(s.str());
958 // We need an additional byte for storing \0 that is not on disk
959 char* NewValue = (char*)malloc(length+1);
961 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
966 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
967 if ( item_read != 1 ) {
969 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
970 ElVal->SetValue("gdcm::UnRead");
973 ElVal->SetValue(NewValue);
978 * \ingroup gdcmHeader
979 * \brief Loads the element while preserving the current
980 * underlying file position indicator as opposed to
981 * to LoadElementValue that modifies it.
982 * @param ElVal Element whose value shall be loaded.
985 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
986 long PositionOnEntry = ftell(fp);
987 LoadElementValue(ElVal);
988 fseek(fp, PositionOnEntry, SEEK_SET);
992 * \ingroup gdcmHeader
993 * \brief Reads a supposed to be 16 Bits integer
994 * \ (swaps it depending on processor endianity)
996 * @return integer acts as a boolean
998 guint16 gdcmHeader::ReadInt16(void) {
1001 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1002 if ( item_read != 1 ) {
1003 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1005 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1007 dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1017 * \ingroup gdcmHeader
1018 * \brief Reads a supposed to be 32 Bits integer
1019 * \ (swaps it depending on processor endianity)
1023 guint32 gdcmHeader::ReadInt32(void) {
1026 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1027 if ( item_read != 1 ) {
1028 //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1030 // dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1032 dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");
1042 * \ingroup gdcmHeader
1047 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1049 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1051 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1052 "failed to Locate gdcmElValue");
1053 return (gdcmElValue*)0;
1059 * \ingroup gdcmHeader
1060 * \brief Build a new Element Value from all the low level arguments.
1061 * Check for existence of dictionary entry, and build
1062 * a default one when absent.
1063 * @param Group group of the underlying DictEntry
1064 * @param Elem element of the underlying DictEntry
1066 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1067 // Find out if the tag we encountered is in the dictionaries:
1068 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1070 NewTag = new gdcmDictEntry(Group, Elem);
1072 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1074 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1075 "failed to allocate gdcmElValue");
1076 return (gdcmElValue*)0;
1082 * \ingroup gdcmHeader
1087 * \return integer acts as a boolean
1089 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value, guint16 Group, guint16 Elem ) {
1091 // TODO : FIXME JPRx
1093 // on (je) cree une Elvalue ne contenant pas de valeur
1094 // on l'ajoute au ElValSet
1095 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1096 // --> devrait pouvoir etre fait + simplement ???
1098 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1099 PubElValSet.Add(nvElValue);
1100 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1106 * \ingroup gdcmHeader
1107 * \brief Modify or (Creates if not found) an element
1108 * @param Value new value
1111 * \return integer acts as a boolean
1114 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1116 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1117 PubElValSet.Add(nvElValue);
1118 std::string v = Value;
1119 PubElValSet.SetElValueByNumber(v, Group, Elem);
1125 * \ingroup gdcmHeader
1126 * \brief Set a new value if the invoked element exists
1130 * \return integer acts as a boolean
1132 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1134 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1135 std::string v = Value;
1136 PubElValSet.SetElValueByNumber(v, Group, Elem);
1142 * \ingroup gdcmHeader
1143 * \brief Checks if a given ElValue (group,number)
1144 * \ exists in the Public ElValSet
1147 * @return integer acts as a boolean
1150 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1151 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1155 * \ingroup gdcmHeader
1156 * \brief Build a new Element Value from all the low level arguments.
1157 * Check for existence of dictionary entry, and build
1158 * a default one when absent.
1159 * @param Name Name of the underlying DictEntry
1161 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1163 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1165 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1167 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1169 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1170 "failed to allocate gdcmElValue");
1171 return (gdcmElValue*)0;
1177 * \ingroup gdcmHeader
1178 * \brief Read the next tag but WITHOUT loading it's value
1179 * @return On succes the newly created ElValue, NULL on failure.
1181 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1184 gdcmElValue * NewElVal;
1189 //if ( (g==0x7fe0) && (n==0x0010) )
1192 // We reached the EOF (or an error occured) and header parsing
1193 // has to be considered as finished.
1194 return (gdcmElValue *)0;
1196 NewElVal = NewElValueByNumber(g, n);
1198 FindLength(NewElVal);
1201 return (gdcmElValue *)0;
1203 NewElVal->SetOffset(ftell(fp));
1204 //if ( (g==0x7fe0) && (n==0x0010) )
1209 * \ingroup gdcmHeader
1210 * \brief Apply some heuristics to predict wether the considered
1211 * element value contains/represents an integer or not.
1212 * @param ElVal The element value on which to apply the predicate.
1213 * @return The result of the heuristical predicate.
1215 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1216 guint16 group = ElVal->GetGroup();
1217 guint16 element = ElVal->GetElement();
1218 std::string vr = ElVal->GetVR();
1219 guint32 length = ElVal->GetLength();
1221 // When we have some semantics on the element we just read, and if we
1222 // a priori know we are dealing with an integer, then we shall be
1223 // able to swap it's element value properly.
1224 if ( element == 0 ) { // This is the group length of the group
1228 dbg.Error("gdcmHeader::IsAnInteger",
1229 "Erroneous Group Length element length.");
1232 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1239 * \ingroup gdcmHeader
1240 * \brief Recover the offset (from the beginning of the file) of the pixels.
1242 size_t gdcmHeader::GetPixelOffset(void) {
1243 // If this file complies with the norm we should encounter the
1244 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1245 // the group that contains the pixel data (hence the "Pixel Data"
1246 // is found by indirection through the "Image Location").
1247 // Inside the group pointed by "Image Location" the searched element
1248 // is conventionally the element 0x0010 (when the norm is respected).
1249 // When the "Image Location" is absent we default to group 0x7fe0.
1252 std::string ImageLocation = GetPubElValByName("Image Location");
1253 if ( ImageLocation == GDCM_UNFOUND ) {
1256 grPixel = (guint16) atoi( ImageLocation.c_str() );
1258 if (grPixel != 0x7fe0)
1259 // This is a kludge for old dirty Philips imager.
1264 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1267 return PixelElement->GetOffset();
1273 * \ingroup gdcmHeader
1274 * \brief Searches both the public and the shadow dictionary (when they
1275 * exist) for the presence of the DictEntry with given
1276 * group and element. The public dictionary has precedence on the
1278 * @param group group of the searched DictEntry
1279 * @param element element of the searched DictEntry
1280 * @return Corresponding DictEntry when it exists, NULL otherwise.
1282 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1284 gdcmDictEntry * found = (gdcmDictEntry*)0;
1285 if (!RefPubDict && !RefShaDict) {
1286 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1287 "we SHOULD have a default dictionary");
1290 found = RefPubDict->GetTagByNumber(group, element);
1295 found = RefShaDict->GetTagByNumber(group, element);
1303 * \ingroup gdcmHeader
1304 * \brief Searches both the public and the shadow dictionary (when they
1305 * exist) for the presence of the DictEntry with given name.
1306 * The public dictionary has precedence on the shadow one.
1307 * @param Name name of the searched DictEntry
1308 * @return Corresponding DictEntry when it exists, NULL otherwise.
1310 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1311 gdcmDictEntry * found = (gdcmDictEntry*)0;
1312 if (!RefPubDict && !RefShaDict) {
1313 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1314 "we SHOULD have a default dictionary");
1317 found = RefPubDict->GetTagByName(Name);
1322 found = RefShaDict->GetTagByName(Name);
1330 * \ingroup gdcmHeader
1331 * \brief Searches within the public dictionary for element value of
1333 * @param group Group of the researched tag.
1334 * @param element Element of the researched tag.
1335 * @return Corresponding element value when it exists, and the string
1336 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1338 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1339 return PubElValSet.GetElValueByNumber(group, element);
1343 * \ingroup gdcmHeader
1344 * \brief Searches within the public dictionary for element value
1345 * representation of a given tag.
1347 * Obtaining the VR (Value Representation) might be needed by caller
1348 * to convert the string typed content to caller's native type
1349 * (think of C++ vs Python). The VR is actually of a higher level
1350 * of semantics than just the native C++ type.
1351 * @param group Group of the researched tag.
1352 * @param element Element of the researched tag.
1353 * @return Corresponding element value representation when it exists,
1354 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1356 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1357 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1359 return GDCM_UNFOUND;
1360 return elem->GetVR();
1364 * \ingroup gdcmHeader
1365 * \brief Searches within the public dictionary for element value of
1367 * @param TagName name of the researched element.
1368 * @return Corresponding element value when it exists, and the string
1369 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1371 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1372 return PubElValSet.GetElValueByName(TagName);
1376 * \ingroup gdcmHeader
1377 * \brief Searches within the elements parsed with the public dictionary for
1378 * the element value representation of a given tag.
1380 * Obtaining the VR (Value Representation) might be needed by caller
1381 * to convert the string typed content to caller's native type
1382 * (think of C++ vs Python). The VR is actually of a higher level
1383 * of semantics than just the native C++ type.
1384 * @param TagName name of the researched element.
1385 * @return Corresponding element value representation when it exists,
1386 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1388 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1389 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1391 return GDCM_UNFOUND;
1392 return elem->GetVR();
1396 * \ingroup gdcmHeader
1397 * \brief Searches within elements parsed with the SHADOW dictionary
1398 * for the element value of a given tag.
1399 * @param group Group of the researched tag.
1400 * @param element Element of the researched tag.
1401 * @return Corresponding element value representation when it exists,
1402 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1404 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1405 return ShaElValSet.GetElValueByNumber(group, element);
1409 * \ingroup gdcmHeader
1410 * \brief Searches within the elements parsed with the SHADOW dictionary
1411 * for the element value representation of a given tag.
1413 * Obtaining the VR (Value Representation) might be needed by caller
1414 * to convert the string typed content to caller's native type
1415 * (think of C++ vs Python). The VR is actually of a higher level
1416 * of semantics than just the native C++ type.
1417 * @param group Group of the researched tag.
1418 * @param element Element of the researched tag.
1419 * @return Corresponding element value representation when it exists,
1420 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1422 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1423 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1425 return GDCM_UNFOUND;
1426 return elem->GetVR();
1430 * \ingroup gdcmHeader
1431 * \brief Searches within the elements parsed with the shadow dictionary
1432 * for an element value of given tag.
1433 * @param TagName name of the researched element.
1434 * @return Corresponding element value when it exists, and the string
1435 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1437 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1438 return ShaElValSet.GetElValueByName(TagName);
1442 * \ingroup gdcmHeader
1443 * \brief Searches within the elements parsed with the shadow dictionary for
1444 * the element value representation of a given tag.
1446 * Obtaining the VR (Value Representation) might be needed by caller
1447 * to convert the string typed content to caller's native type
1448 * (think of C++ vs Python). The VR is actually of a higher level
1449 * of semantics than just the native C++ type.
1450 * @param TagName name of the researched element.
1451 * @return Corresponding element value representation when it exists,
1452 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1454 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1455 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1457 return GDCM_UNFOUND;
1458 return elem->GetVR();
1462 * \ingroup gdcmHeader
1463 * \brief Searches within elements parsed with the public dictionary
1464 * and then within the elements parsed with the shadow dictionary
1465 * for the element value of a given tag.
1466 * @param group Group of the researched tag.
1467 * @param element Element of the researched tag.
1468 * @return Corresponding element value representation when it exists,
1469 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1471 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1472 std::string pub = GetPubElValByNumber(group, element);
1475 return GetShaElValByNumber(group, element);
1479 * \ingroup gdcmHeader
1480 * \brief Searches within elements parsed with the public dictionary
1481 * and then within the elements parsed with the shadow dictionary
1482 * for the element value representation of a given tag.
1484 * Obtaining the VR (Value Representation) might be needed by caller
1485 * to convert the string typed content to caller's native type
1486 * (think of C++ vs Python). The VR is actually of a higher level
1487 * of semantics than just the native C++ type.
1488 * @param group Group of the researched tag.
1489 * @param element Element of the researched tag.
1490 * @return Corresponding element value representation when it exists,
1491 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1493 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1494 std::string pub = GetPubElValRepByNumber(group, element);
1497 return GetShaElValRepByNumber(group, element);
1501 * \ingroup gdcmHeader
1502 * \brief Searches within elements parsed with the public dictionary
1503 * and then within the elements parsed with the shadow dictionary
1504 * for the element value of a given tag.
1505 * @param TagName name of the researched element.
1506 * @return Corresponding element value when it exists,
1507 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1509 std::string gdcmHeader::GetElValByName(std::string TagName) {
1510 std::string pub = GetPubElValByName(TagName);
1513 return GetShaElValByName(TagName);
1517 * \ingroup gdcmHeader
1518 * \brief Searches within elements parsed with the public dictionary
1519 * and then within the elements parsed with the shadow dictionary
1520 * for the element value representation of a given tag.
1522 * Obtaining the VR (Value Representation) might be needed by caller
1523 * to convert the string typed content to caller's native type
1524 * (think of C++ vs Python). The VR is actually of a higher level
1525 * of semantics than just the native C++ type.
1526 * @param TagName name of the researched element.
1527 * @return Corresponding element value representation when it exists,
1528 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1530 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1531 std::string pub = GetPubElValRepByName(TagName);
1534 return GetShaElValRepByName(TagName);
1538 * \ingroup gdcmHeader
1539 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1540 * through it's (group, element) and modifies it's content with
1542 * @param content new value to substitute with
1543 * @param group group of the ElVal to modify
1544 * @param element element of the ElVal to modify
1546 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1549 //TODO : homogeneiser les noms : SetPubElValByNumber qui appelle PubElValSet.SetElValueByNumber
1550 // pourquoi pas SetPubElValueByNumber ??
1553 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1557 * \ingroup gdcmHeader
1558 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1559 * through tag name and modifies it's content with the given value.
1560 * @param content new value to substitute with
1561 * @param TagName name of the tag to be modified
1563 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1564 return ( PubElValSet.SetElValueByName (content, TagName) );
1568 * \ingroup gdcmHeader
1569 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1570 * through it's (group, element) and modifies it's length with
1572 * \warning Use with extreme caution.
1573 * @param length new length to substitute with
1574 * @param group group of the ElVal to modify
1575 * @param element element of the ElVal to modify
1576 * @return 1 on success, 0 otherwise.
1579 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1581 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1585 * \ingroup gdcmHeader
1586 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1587 * through it's (group, element) and modifies it's content with
1589 * @param content new value to substitute with
1590 * @param group group of the ElVal to modify
1591 * @param element element of the ElVal to modify
1592 * @return 1 on success, 0 otherwise.
1594 int gdcmHeader::SetShaElValByNumber(std::string content,
1595 guint16 group, guint16 element) {
1596 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1600 * \ingroup gdcmHeader
1601 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1602 * through tag name and modifies it's content with the given value.
1603 * @param content new value to substitute with
1604 * @param ShadowTagName name of the tag to be modified
1606 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1607 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1611 * \ingroup gdcmHeader
1612 * \brief Parses the header of the file but WITHOUT loading element values.
1614 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1615 gdcmElValue * newElValue = (gdcmElValue *)0;
1619 while ( (newElValue = ReadNextElement()) ) {
1620 SkipElementValue(newElValue);
1621 PubElValSet.Add(newElValue);
1626 * \ingroup gdcmHeader
1627 * \brief This predicate, based on hopefully reasonnable heuristics,
1628 * decides whether or not the current gdcmHeader was properly parsed
1629 * and contains the mandatory information for being considered as
1630 * a well formed and usable image.
1631 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1634 bool gdcmHeader::IsReadable(void) {
1635 if ( GetElValByName("Image Dimensions") != GDCM_UNFOUND
1636 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1639 if ( GetElValByName("Bits Allocated") == GDCM_UNFOUND )
1641 if ( GetElValByName("Bits Stored") == GDCM_UNFOUND )
1643 if ( GetElValByName("High Bit") == GDCM_UNFOUND )
1645 if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1651 * \ingroup gdcmHeader
1652 * \brief Small utility function that creates a new manually crafted
1653 * (as opposed as read from the file) gdcmElValue with user
1654 * specified name and adds it to the public tag hash table.
1655 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1656 * @param NewTagName The name to be given to this new tag.
1657 * @param VR The Value Representation to be given to this new tag.
1658 * @ return The newly hand crafted Element Value.
1660 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName, std::string VR) {
1661 gdcmElValue* NewElVal = (gdcmElValue*)0;
1662 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1663 guint32 FreeElem = 0;
1664 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1666 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1667 if (FreeElem == UINT32_MAX) {
1668 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1669 "Group 0xffff in Public Dict is full");
1670 return (gdcmElValue*)0;
1672 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1673 VR, "GDCM", NewTagName);
1674 NewElVal = new gdcmElValue(NewEntry);
1675 PubElValSet.Add(NewElVal);
1680 * \ingroup gdcmHeader
1681 * \brief Loads the element values of all the elements present in the
1682 * public tag based hash table.
1684 void gdcmHeader::LoadElements(void) {
1686 TagElValueHT ht = PubElValSet.GetTagHt();
1687 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1688 LoadElementValue(tag->second);
1692 // Load 'non string' values
1693 std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);
1694 if( PhotometricInterpretation == "PALETTE COLOR " ){
1695 LoadElementVoidArea(0x0028,0x1200); // gray LUT
1696 LoadElementVoidArea(0x0028,0x1201); // R LUT
1697 LoadElementVoidArea(0x0028,0x1202); // G LUT
1698 LoadElementVoidArea(0x0028,0x1203); // B LUT
1700 LoadElementVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1701 LoadElementVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1702 LoadElementVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1705 // --------------------------------------------------------------
1706 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1708 // if recognition code tells us we deal with a LibIDO image
1709 // we switch lineNumber and columnNumber
1711 std::string RecCode;
1712 RecCode = GetPubElValByNumber(0x0008, 0x0010);
1713 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1714 RecCode == "CANRME_AILIBOD1_1." ) {
1715 filetype = ACR_LIBIDO;
1716 std::string rows = GetPubElValByNumber(0x0028, 0x0010);
1717 std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1718 SetPubElValByNumber(columns, 0x0028, 0x0010);
1719 SetPubElValByNumber(rows , 0x0028, 0x0011);
1721 // ----------------- End of Special Patch ----------------
1725 * \ingroup gdcmHeader
1729 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1730 PubElValSet.Print(os);
1734 * \ingroup gdcmHeader
1738 void gdcmHeader::PrintPubDict(std::ostream & os) {
1739 RefPubDict->Print(os);
1743 * \ingroup gdcmHeader
1747 int gdcmHeader::Write(FILE * fp, FileType type) {
1748 return PubElValSet.Write(fp, type);
1752 // ------------------------ 'non string' elements related functions
1756 * \ingroup gdcmHeader
1757 * \brief Loads (from disk) the element content
1758 * when a string is not suitable
1760 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1761 gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1764 size_t o =(size_t)Element->GetOffset();
1765 fseek(fp, o, SEEK_SET);
1766 int l=Element->GetLength();
1767 void * a = malloc(l);
1769 std::cout << "Big Broblem (LoadElementVoidArea, malloc) "
1770 << std::hex << Group << " " << Elem << std::endl;
1773 int res = PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1774 // TODO check the result
1775 size_t l2 = fread(a, 1, l ,fp);
1777 std::cout << "Big Broblem (LoadElementVoidArea, fread) "
1778 << std::hex << Group << " " << Elem << std::endl;
1785 * \ingroup gdcmHeader
1786 * \brief Gets (from Header) the offset of a 'non string' element value
1787 * \ (LoadElementValue has already be executed)
1790 * @return File Offset of the Element Value
1792 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1793 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1795 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1796 "failed to Locate gdcmElValue");
1799 return elValue->GetOffset();
1803 * \ingroup gdcmHeader
1804 * \brief Gets (from Header) a 'non string' element value
1805 * \ (LoadElementValue has already be executed)
1808 * @return Pointer to the 'non string' area
1811 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1812 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1814 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1815 "failed to Locate gdcmElValue");
1818 return elValue->GetVoidArea();
1823 // =============================================================================
1824 // Heuristics based accessors
1825 //==============================================================================
1828 // TODO : move to an other file.
1832 * \ingroup gdcmHeader
1833 * \brief Retrieve the number of columns of image.
1834 * @return The encountered size when found, 0 by default.
1836 int gdcmHeader::GetXSize(void) {
1837 // We cannot check for "Columns" because the "Columns" tag is present
1838 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1839 std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1840 if (StrSize == GDCM_UNFOUND)
1842 return atoi(StrSize.c_str());
1846 * \ingroup gdcmHeader
1847 * \brief Retrieve the number of lines of image.
1848 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1849 * @return The encountered size when found, 1 by default.
1851 int gdcmHeader::GetYSize(void) {
1852 // We cannot check for "Rows" because the "Rows" tag is present
1853 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1854 std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1855 if (StrSize != GDCM_UNFOUND)
1856 return atoi(StrSize.c_str());
1860 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1861 // hence be a signal (1d image). So we default to 1:
1866 * \ingroup gdcmHeader
1867 * \brief Retrieve the number of planes of volume or the number
1868 * of frames of a multiframe.
1869 * \warning When present we consider the "Number of Frames" as the third
1870 * dimension. When absent we consider the third dimension as
1871 * being the "Planes" tag content.
1872 * @return The encountered size when found, 1 by default.
1874 int gdcmHeader::GetZSize(void) {
1875 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1876 // as the third dimension.
1877 std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
1878 if (StrSize != GDCM_UNFOUND)
1879 return atoi(StrSize.c_str());
1881 // We then consider the "Planes" entry as the third dimension [we
1882 // cannot retrieve by name since "Planes tag is present both in
1883 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1884 StrSize = GetPubElValByNumber(0x0028,0x0012);
1885 if (StrSize != GDCM_UNFOUND)
1886 return atoi(StrSize.c_str());
1891 * \ingroup gdcmHeader
1892 * \brief Retrieve the number of Bits Stored
1893 * (as opposite to number of Bits Allocated)
1895 * @return The encountered number of Bits Stored, 0 by default.
1897 int gdcmHeader::GetBitsStored(void) {
1898 std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
1899 if (StrSize == GDCM_UNFOUND)
1901 return atoi(StrSize.c_str());
1906 * \ingroup gdcmHeader
1907 * \brief Retrieve the number of Samples Per Pixel
1908 * (1 : gray level, 3 : RGB)
1910 * @return The encountered number of Samples Per Pixel, 1 by default.
1912 int gdcmHeader::GetSamplesPerPixel(void) {
1913 std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
1914 if (StrSize == GDCM_UNFOUND)
1915 return 1; // Well, it's supposed to be mandatory ...
1916 return atoi(StrSize.c_str());
1920 * \ingroup gdcmHeader
1921 * \brief Retrieve the Planar Configuration for RGB images
1922 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1924 * @return The encountered Planar Configuration, 0 by default.
1926 int gdcmHeader::GetPlanarConfiguration(void) {
1927 std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
1928 if (StrSize == GDCM_UNFOUND)
1930 return atoi(StrSize.c_str());
1934 * \ingroup gdcmHeader
1935 * \brief Return the size (in bytes) of a single pixel of data.
1936 * @return The size in bytes of a single pixel of data.
1939 int gdcmHeader::GetPixelSize(void) {
1940 std::string PixelType = GetPixelType();
1941 if (PixelType == "8U" || PixelType == "8S")
1943 if (PixelType == "16U" || PixelType == "16S")
1945 if (PixelType == "32U" || PixelType == "32S")
1947 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1952 * \ingroup gdcmHeader
1953 * \brief Build the Pixel Type of the image.
1954 * Possible values are:
1955 * - 8U unsigned 8 bit,
1956 * - 8S signed 8 bit,
1957 * - 16U unsigned 16 bit,
1958 * - 16S signed 16 bit,
1959 * - 32U unsigned 32 bit,
1960 * - 32S signed 32 bit,
1961 * \warning 12 bit images appear as 16 bit.
1964 std::string gdcmHeader::GetPixelType(void) {
1965 std::string BitsAlloc;
1966 BitsAlloc = GetElValByName("Bits Allocated");
1967 if (BitsAlloc == GDCM_UNFOUND) {
1968 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1969 BitsAlloc = std::string("16");
1971 if (BitsAlloc == "12")
1972 BitsAlloc = std::string("16");
1975 Signed = GetElValByName("Pixel Representation");
1976 if (Signed == GDCM_UNFOUND) {
1977 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1978 BitsAlloc = std::string("0");
1981 Signed = std::string("U");
1983 Signed = std::string("S");
1985 return( BitsAlloc + Signed);
1989 * \ingroup gdcmHeader
1990 * \brief gets the info from 0002,0010 : Transfert Syntax
1992 * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
1994 std::string gdcmHeader::GetTransferSyntaxName(void) {
1995 std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
1996 if (TransfertSyntax == GDCM_UNFOUND) {
1997 dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
1998 return "Uncompressed ACR-NEMA";
2000 // we do it only when we need it
2001 gdcmTS * ts = gdcmGlobal::GetTS();
2002 std::string tsName=ts->GetValue(TransfertSyntax);
2003 //delete ts; // Seg Fault when deleted ?!
2007 // -------------------------------- Lookup Table related functions ------------
2010 * \ingroup gdcmHeader
2011 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2013 * @return Lookup Table Length
2014 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2017 int gdcmHeader::GetLUTLength(void) {
2018 std::vector<std::string> tokens;
2022 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2023 std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2024 if (LutDescriptionR == GDCM_UNFOUND)
2026 std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2027 if (LutDescriptionG == GDCM_UNFOUND)
2029 std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2030 if (LutDescriptionB == GDCM_UNFOUND)
2032 if( (LutDescriptionR != LutDescriptionG) || (LutDescriptionR != LutDescriptionB) ) {
2033 dbg.Verbose(0, "gdcmHeader::GetLUTLength: The CLUT R,G,B are not equal");
2036 std::cout << "Lut Description " << LutDescriptionR <<std::endl;
2037 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2038 Tokenize (LutDescriptionR, tokens, "\\");
2039 LutLength=atoi(tokens[0].c_str());
2040 //LutDepth=atoi(tokens[1].c_str());
2041 //LutNbits=atoi(tokens[2].c_str());
2047 * \ingroup gdcmHeader
2048 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2050 * @return Lookup Table nBit
2051 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2054 int gdcmHeader::GetLUTNbits(void) {
2055 std::vector<std::string> tokens;
2059 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2060 // Consistency already checked in GetLUTLength
2061 std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2062 if (LutDescription == GDCM_UNFOUND)
2064 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2065 Tokenize (LutDescription, tokens, "\\");
2066 //LutLength=atoi(tokens[0].c_str());
2067 //LutDepth=atoi(tokens[1].c_str());
2068 LutNbits=atoi(tokens[2].c_str());
2075 * \ingroup gdcmHeader
2076 * \brief gets the info from 0028,1201 : Lookup Table Red
2078 * @return Lookup Table Red
2079 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2081 void * gdcmHeader::GetLUTRed(void) {
2082 return GetPubElValVoidAreaByNumber(0x0028,0x1201);
2086 * \ingroup gdcmHeader
2087 * \brief gets the info from 0028,1202 : Lookup Table Green
2089 * @return Lookup Table Red
2090 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2092 void * gdcmHeader::GetLUTGreen(void) {
2093 return GetPubElValVoidAreaByNumber(0x0028,0x1202);
2097 * \ingroup gdcmHeader
2098 * \brief gets the info from 0028,1202 : Lookup Table Blue
2100 * @return Lookup Table Blue
2101 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2103 void * gdcmHeader::GetLUTBlue(void) {
2104 return GetPubElValVoidAreaByNumber(0x0028,0x1203);
2108 * \ingroup gdcmHeader
2110 * @return Lookup Table RGB
2111 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2112 * \ and (0028,1201),(0028,1202),(0028,1202) are found
2113 * \warning : hazardous ! Use better GetPubElValVoidAreaByNumber
2115 void * gdcmHeader::GetLUTRGB(void) {
2116 // Not so easy : see
2117 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2118 // and OT-PAL-8-face.dcm
2120 if (GetPubElValByNumber(0x0028,0x0004) == GDCM_UNFOUND) {
2121 dbg.Verbose(0, "gdcmHeader::GetLUTRGB: unfound Photometric Interpretation");
2124 void * LutR,*LutG,*LutB;
2127 // Maybe, some day we get an image
2128 // that respects the definition ...
2129 // Let's consider no ones does.
2134 int nBits=GetLUTNbits();
2135 // a virer quand on aura trouve UNE image
2136 // qui correspond VRAIMENT à la definition !
2137 std::cout << "l " << l << " nBits " << nBits;
2141 LutR =GetPubElValVoidAreaByNumber(0x0028,0x1201);
2142 LutG =GetPubElValVoidAreaByNumber(0x0028,0x1202);
2143 LutB =GetPubElValVoidAreaByNumber(0x0028,0x1203);
2145 // Warning : Any value for nBits as to be considered as 8
2146 // Any value for Length as to be considered as 256
2149 // Just wait before removing the following code
2152 guint16 * LUTRGB, *rgb;
2153 LUTRGB = rgb = (guint16 *) malloc(3*l*sizeof( guint16));
2154 guint16 * r = (guint16 *)LutR;
2155 guint16 * g = (guint16 *)LutG;
2156 guint16 * b = (guint16 *)LutB;
2157 for(int i=0;i<l;i++) {
2165 */ { // we assume it's always 8 Bits
2166 l=256; // we assume ...
2167 unsigned char * LUTRGB, *rgb;
2168 LUTRGB = rgb = (unsigned char *) malloc(3*l*sizeof( char));
2169 unsigned char * r = (unsigned char *)LutR;
2170 unsigned char * g = (unsigned char *)LutG;
2171 unsigned char * b = (unsigned char *)LutB;
2172 for(int i=0;i<l;i++) {
2173 //std::cout << "lut16 " << i << " : " << *r << " " << *g << " " << *b << std::endl;
2174 printf("lut 8 %d : %d %d %d \n",i,*r,*g,*b);
2179 free(LutR); free(LutB); free(LutG);