1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.95 2003/10/06 13:37:25 jpr Exp $
3 #include "gdcmHeader.h"
11 #include <netinet/in.h>
13 #include <cctype> // for isalpha
18 // Refer to gdcmHeader::CheckSwap()
19 #define HEADER_LENGTH_TO_READ 256
20 // Refer to gdcmHeader::SetMaxSizeLoadElementValue()
21 //#define _MaxSizeLoadElementValue_ 1024
22 #define _MaxSizeLoadElementValue_ 4096
27 void gdcmHeader::Initialise(void) {
28 dicom_vr = gdcmGlobal::GetVR();
29 dicom_ts = gdcmGlobal::GetTS();
30 Dicts = gdcmGlobal::GetDicts();
31 RefPubDict = Dicts->GetDefaultPubDict();
32 RefShaDict = (gdcmDict*)0;
39 * @param exception_on_error
41 gdcmHeader::gdcmHeader(const char *InFilename, bool exception_on_error) {
42 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
43 filename = InFilename;
45 if ( !OpenFile(exception_on_error))
55 * @param exception_on_error
57 gdcmHeader::gdcmHeader(bool exception_on_error) {
58 SetMaxSizeLoadElementValue(_MaxSizeLoadElementValue_);
65 * @param exception_on_error
68 bool gdcmHeader::OpenFile(bool exception_on_error)
69 throw(gdcmFileError) {
70 fp=fopen(filename.c_str(),"rb");
71 if(exception_on_error) {
73 throw gdcmFileError("gdcmHeader::gdcmHeader(const char *, bool)");
77 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
84 * @return TRUE if the close was successfull
86 bool gdcmHeader::CloseFile(void) {
87 int closed = fclose(fp);
96 * \brief Canonical destructor.
98 gdcmHeader::~gdcmHeader (void) {
99 dicom_vr = (gdcmVR*)0;
100 Dicts = (gdcmDictSet*)0;
101 RefPubDict = (gdcmDict*)0;
102 RefShaDict = (gdcmDict*)0;
108 // ---> Warning : This fourth fiels is NOT part
109 // of the 'official' Dicom Dictionnary
110 // and should NOT be used.
111 // (Not defined for all the groups
112 // may be removed in a future release)
115 // META Meta Information
127 // NMI Nuclear Medicine
129 // BFS Basic Film Session
130 // BFB Basic Film Box
131 // BIB Basic Image Box
147 * \ingroup gdcmHeader
148 * \brief Discover what the swap code is (among little endian, big endian,
149 * bad little endian, bad big endian).
152 void gdcmHeader::CheckSwap()
154 // The only guaranted way of finding the swap code is to find a
155 // group tag since we know it's length has to be of four bytes i.e.
156 // 0x00000004. Finding the swap code in then straigthforward. Trouble
157 // occurs when we can't find such group...
159 guint32 x=4; // x : for ntohs
160 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
164 char deb[HEADER_LENGTH_TO_READ];
166 // First, compare HostByteOrder and NetworkByteOrder in order to
167 // determine if we shall need to swap bytes (i.e. the Endian type).
173 // The easiest case is the one of a DICOM header, since it possesses a
174 // file preamble where it suffice to look for the string "DICM".
175 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
178 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
179 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
180 // Next, determine the value representation (VR). Let's skip to the
181 // first element (0002, 0000) and check there if we find "UL"
182 // - or "OB" if the 1st one is (0002,0001) -,
183 // in which case we (almost) know it is explicit VR.
184 // WARNING: if it happens to be implicit VR then what we will read
185 // is the length of the group. If this ascii representation of this
186 // length happens to be "UL" then we shall believe it is explicit VR.
187 // FIXME: in order to fix the above warning, we could read the next
188 // element value (or a couple of elements values) in order to make
189 // sure we are not commiting a big mistake.
191 // * the 128 bytes of File Preamble (often padded with zeroes),
192 // * the 4 bytes of "DICM" string,
193 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
194 // i.e. a total of 136 bytes.
197 // Use gdcmHeader::dicom_vr to test all the possibilities
198 // instead of just checking for UL, OB and UI !?
199 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
200 (memcmp(entCur, "OB", (size_t)2) == 0) ||
201 (memcmp(entCur, "UI", (size_t)2) == 0) )
203 filetype = ExplicitVR;
204 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
205 "explicit Value Representation");
207 filetype = ImplicitVR;
208 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
209 "not an explicit Value Representation");
213 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
214 "HostByteOrder != NetworkByteOrder");
217 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
218 "HostByteOrder = NetworkByteOrder");
221 // Position the file position indicator at first tag (i.e.
222 // after the file preamble and the "DICM" string).
224 fseek (fp, 132L, SEEK_SET);
228 // Alas, this is not a DicomV3 file and whatever happens there is no file
229 // preamble. We can reset the file position indicator to where the data
230 // is (i.e. the beginning of the file).
231 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
234 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
235 // By clean we mean that the length of the first tag is written down.
236 // If this is the case and since the length of the first group HAS to be
237 // four (bytes), then determining the proper swap code is straightforward.
240 // We assume the array of char we are considering contains the binary
241 // representation of a 32 bits integer. Hence the following dirty
243 s = *((guint32 *)(entCur));
263 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
264 "ACR/NEMA unfound swap info (time to raise bets)");
267 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
268 // It is time for despaired wild guesses. So, let's assume this file
269 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
270 // not present. Then the only info we have is the net2host one.
280 * \ingroup gdcmHeader
283 void gdcmHeader::SwitchSwapToBigEndian(void) {
284 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
285 "Switching to BigEndian mode.");
303 * \ingroup gdcmHeader
304 * \brief Find the value representation of the current tag.
307 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
308 if (filetype != ExplicitVR)
314 char msg[100]; // for sprintf. Sorry
316 long PositionOnEntry = ftell(fp);
317 // Warning: we believe this is explicit VR (Value Representation) because
318 // we used a heuristic that found "UL" in the first tag. Alas this
319 // doesn't guarantee that all the tags will be in explicit VR. In some
320 // cases (see e-film filtered files) one finds implicit VR tags mixed
321 // within an explicit VR file. Hence we make sure the present tag
322 // is in explicit VR and try to fix things if it happens not to be
324 bool RealExplicit = true;
326 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
328 vr = std::string(VR);
330 // Assume we are reading a falsely explicit VR file i.e. we reached
331 // a tag where we expect reading a VR but are in fact we read the
332 // first to bytes of the length. Then we will interogate (through find)
333 // the dicom_vr dictionary with oddities like "\004\0" which crashes
334 // both GCC and VC++ implementations of the STL map. Hence when the
335 // expected VR read happens to be non-ascii characters we consider
336 // we hit falsely explicit VR tag.
338 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
339 RealExplicit = false;
341 // CLEANME searching the dicom_vr at each occurence is expensive.
342 // PostPone this test in an optional integrity check at the end
343 // of parsing or only in debug mode.
344 if ( RealExplicit && !dicom_vr->Count(vr) )
347 if ( RealExplicit ) {
348 if ( ElVal->IsVrUnknown() ) {
349 // When not a dictionary entry, we can safely overwrite the vr.
353 if ( ElVal->GetVR() == vr ) {
354 // The vr we just read and the dictionary agree. Nothing to do.
357 // The vr present in the file and the dictionary disagree. We assume
358 // the file writer knew best and use the vr of the file. Since it would
359 // be unwise to overwrite the vr of a dictionary (since it would
360 // compromise it's next user), we need to clone the actual DictEntry
361 // and change the vr for the read one.
362 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
367 ElVal->SetDictEntry(NewTag);
371 // We thought this was explicit VR, but we end up with an
372 // implicit VR tag. Let's backtrack.
374 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
375 ElVal->GetGroup(),ElVal->GetElement());
376 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
378 fseek(fp, PositionOnEntry, SEEK_SET);
379 // When this element is known in the dictionary we shall use, e.g. for
380 // the semantics (see the usage of IsAnInteger), the vr proposed by the
381 // dictionary entry. Still we have to flag the element as implicit since
382 // we know now our assumption on expliciteness is not furfilled.
384 if ( ElVal->IsVrUnknown() )
385 ElVal->SetVR("Implicit");
386 ElVal->SetImplicitVr();
390 * \ingroup gdcmHeader
391 * \brief Determines if the Transfer Syntax was already encountered
392 * and if it corresponds to a ImplicitVRLittleEndian one.
394 * @return True when ImplicitVRLittleEndian found. False in all other cases.
396 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
397 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
400 LoadElementValueSafe(Element);
401 std::string Transfer = Element->GetValue();
402 if ( Transfer == "1.2.840.10008.1.2" )
408 * \ingroup gdcmHeader
409 * \brief Determines if the Transfer Syntax was already encountered
410 * and if it corresponds to a ExplicitVRLittleEndian one.
412 * @return True when ExplicitVRLittleEndian found. False in all other cases.
414 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
415 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
418 LoadElementValueSafe(Element);
419 std::string Transfer = Element->GetValue();
420 if ( Transfer == "1.2.840.10008.1.2.1" )
426 * \ingroup gdcmHeader
427 * \brief Determines if the Transfer Syntax was already encountered
428 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
430 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
432 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
433 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
436 LoadElementValueSafe(Element);
437 std::string Transfer = Element->GetValue();
438 if ( Transfer == "1.2.840.10008.1.2.1.99" )
444 * \ingroup gdcmHeader
445 * \brief Determines if the Transfer Syntax was already encountered
446 * and if it corresponds to a Explicit VR Big Endian one.
448 * @return True when big endian found. False in all other cases.
450 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
451 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
454 LoadElementValueSafe(Element);
455 std::string Transfer = Element->GetValue();
456 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
462 * \ingroup gdcmHeader
463 * \brief Determines if the Transfer Syntax was already encountered
464 * and if it corresponds to a JPEGBaseLineProcess1 one.
466 * @return True when JPEGBaseLineProcess1found. False in all other cases.
468 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
469 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
472 LoadElementValueSafe(Element);
473 std::string Transfer = Element->GetValue();
474 if ( Transfer == "1.2.840.10008.1.2.4.50" )
480 * \ingroup gdcmHeader
485 bool gdcmHeader::IsJPEGLossless(void) {
486 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
487 // faire qq chose d'intelligent a la place de ça
490 LoadElementValueSafe(Element);
491 const char * Transfert = Element->GetValue().c_str();
492 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
493 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
494 if (Element->GetValue() == "1.2.840.10008.1.2.4.57") return true;
501 * \ingroup gdcmHeader
502 * \brief Determines if the Transfer Syntax was already encountered
503 * and if it corresponds to a JPEGExtendedProcess2-4 one.
505 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
507 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
508 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
511 LoadElementValueSafe(Element);
512 std::string Transfer = Element->GetValue();
513 if ( Transfer == "1.2.840.10008.1.2.4.51" )
519 * \ingroup gdcmHeader
520 * \brief Determines if the Transfer Syntax was already encountered
521 * and if it corresponds to a JPEGExtendeProcess3-5 one.
523 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
525 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
526 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
529 LoadElementValueSafe(Element);
530 std::string Transfer = Element->GetValue();
531 if ( Transfer == "1.2.840.10008.1.2.4.52" )
537 * \ingroup gdcmHeader
538 * \brief Determines if the Transfer Syntax was already encountered
539 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
541 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
544 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
545 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
548 LoadElementValueSafe(Element);
549 std::string Transfer = Element->GetValue();
550 if ( Transfer == "1.2.840.10008.1.2.4.53" )
556 * \ingroup gdcmHeader
557 * \brief Determines if the Transfer Syntax was already encountered
558 * and if it corresponds to a RLE Lossless one.
560 * @return True when RLE Lossless found. False in all
563 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
564 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
567 LoadElementValueSafe(Element);
568 std::string Transfer = Element->GetValue();
569 if ( Transfer == "1.2.840.10008.1.2.5" )
575 * \ingroup gdcmHeader
576 * \brief Determines if the Transfer Syntax was already encountered
577 * and if it corresponds to a JPEG200 one.0
579 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
582 bool gdcmHeader::IsJPEG2000(void) {
583 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
586 LoadElementValueSafe(Element);
587 std::string Transfer = Element->GetValue();
588 if ( (Transfer == "1.2.840.10008.1.2.4.90")
589 || (Transfer == "1.2.840.10008.1.2.4.91") )
595 * \ingroup gdcmHeader
596 * \brief Predicate for dicom version 3 file.
597 * @return True when the file is a dicom version 3.
599 bool gdcmHeader::IsDicomV3(void) {
600 if ( (filetype == ExplicitVR)
601 || (filetype == ImplicitVR) )
607 * \ingroup gdcmHeader
608 * \brief When the length of an element value is obviously wrong (because
609 * the parser went Jabberwocky) one can hope improving things by
610 * applying this heuristic.
612 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
613 if ( FoundLength == 0xffffffff)
615 // Sorry for the patch!
616 // XMedCom did the trick to read some nasty GE images ...
617 if (FoundLength == 13)
620 ElVal->SetLength(FoundLength);
624 * \ingroup gdcmHeader
629 guint32 gdcmHeader::FindLengthOB(void) {
630 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
633 long PositionOnEntry = ftell(fp);
634 bool FoundSequenceDelimiter = false;
635 guint32 TotalLength = 0;
638 while ( ! FoundSequenceDelimiter) {
646 TotalLength += 4; // We even have to decount the group and element
648 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
649 char msg[100]; // for sprintf. Sorry
650 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
651 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
656 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
657 FoundSequenceDelimiter = true;
658 else if ( n != 0xe000 ){
659 char msg[100]; // for sprintf. Sorry
660 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\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 std::string vr = ElVal->GetVR();
687 if( (element == 0x0010) && (group == 0x7fe0) ) {
689 dbg.Verbose(2, "gdcmHeader::FindLength: ",
690 "we reached 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();
703 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
704 ElVal->SetLength(FindLengthOB());
707 FixFoundLength(ElVal, length32);
711 // Length is encoded on 2 bytes.
712 length16 = ReadInt16();
714 // We can tell the current file is encoded in big endian (like
715 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
716 // and it's value is the one of the encoding of a big endian file.
717 // In order to deal with such big endian encoded files, we have
718 // (at least) two strategies:
719 // * when we load the "Transfer Syntax" tag with value of big endian
720 // encoding, we raise the proper flags. Then we wait for the end
721 // of the META group (0x0002) among which is "Transfer Syntax",
722 // before switching the swap code to big endian. We have to postpone
723 // the switching of the swap code since the META group is fully encoded
724 // in little endian, and big endian coding only starts at the next
725 // group. The corresponding code can be hard to analyse and adds
726 // many additional unnecessary tests for regular tags.
727 // * the second strategy consists in waiting for trouble, that shall
728 // appear when we find the first group with big endian encoding. This
729 // is easy to detect since the length of a "Group Length" tag (the
730 // ones with zero as element number) has to be of 4 (0x0004). When we
731 // encouter 1024 (0x0400) chances are the encoding changed and we
732 // found a group with big endian encoding.
733 // We shall use this second strategy. In order to make sure that we
734 // can interpret the presence of an apparently big endian encoded
735 // length of a "Group Length" without committing a big mistake, we
736 // add an additional check: we look in the already parsed elements
737 // for the presence of a "Transfer Syntax" whose value has to be "big
738 // endian encoding". When this is the case, chances are we have got our
739 // hands on a big endian encoded file: we switch the swap code to
740 // big endian and proceed...
741 if ( (element == 0x0000) && (length16 == 0x0400) ) {
742 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
743 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
748 SwitchSwapToBigEndian();
749 // Restore the unproperly loaded values i.e. the group, the element
750 // and the dictionary entry depending on them.
751 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
752 guint16 CorrectElem = SwapShort(ElVal->GetElement());
753 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
756 // This correct tag is not in the dictionary. Create a new one.
757 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
759 // FIXME this can create a memory leaks on the old entry that be
760 // left unreferenced.
761 ElVal->SetDictEntry(NewTag);
764 // Heuristic: well some files are really ill-formed.
765 if ( length16 == 0xffff) {
767 //dbg.Verbose(0, "gdcmHeader::FindLength",
768 // "Erroneous element length fixed.");
769 // Actually, length= 0xffff means that we deal with
770 // Unknown Sequence Length
773 FixFoundLength(ElVal, (guint32)length16);
777 // Either implicit VR or a non DICOM conformal (see not below) explicit
778 // VR that ommited the VR of (at least) this element. Farts happen.
779 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
780 // on Data elements "Implicit and Explicit VR Data Elements shall
781 // not coexist in a Data Set and Data Sets nested within it".]
782 // Length is on 4 bytes.
783 FixFoundLength(ElVal, ReadInt32());
787 * \ingroup gdcmHeader
788 * \brief Swaps back the bytes of 4-byte long integer accordingly to
791 * @return The suggested integer.
793 guint32 gdcmHeader::SwapLong(guint32 a) {
798 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
799 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
803 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
807 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
810 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
817 * \ingroup gdcmHeader
818 * \brief Swaps the bytes so they agree with the processor order
819 * @return The properly swaped 16 bits integer.
821 guint16 gdcmHeader::SwapShort(guint16 a) {
822 if ( (sw==4321) || (sw==2143) )
823 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
828 * \ingroup gdcmHeader
833 void gdcmHeader::SkipBytes(guint32 NBytes) {
834 //FIXME don't dump the returned value
835 (void)fseek(fp, (long)NBytes, SEEK_CUR);
839 * \ingroup gdcmHeader
844 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
845 SkipBytes(ElVal->GetLength());
849 * \ingroup gdcmHeader
854 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
857 if ((guint32)NewSize >= (guint32)0xffffffff) {
858 MaxSizeLoadElementValue = 0xffffffff;
861 MaxSizeLoadElementValue = NewSize;
865 * \ingroup gdcmHeader
866 * \brief Loads the element content if it's length is not bigger
867 * than the value specified with
868 * gdcmHeader::SetMaxSizeLoadElementValue()
870 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
872 guint16 group = ElVal->GetGroup();
873 std::string vr= ElVal->GetVR();
874 guint32 length = ElVal->GetLength();
875 bool SkipLoad = false;
877 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
879 // FIXME Sequences not treated yet !
881 // Ne faudrait-il pas au contraire trouver immediatement
882 // une maniere 'propre' de traiter les sequences (vr = SQ)
883 // car commencer par les ignorer risque de conduire a qq chose
884 // qui pourrait ne pas etre generalisable
885 // Well, I'm expecting your code !!!
890 // Heuristic : a sequence "contains" a set of tags (called items). It looks
891 // like the last tag of a sequence (the one that terminates the sequence)
892 // has a group of 0xfffe (with a dummy length).
894 // Actually (fffe e000) tells us an Element is beginning
895 // (fffe e00d) tells us an Element just ended
896 // (fffe e0dd) tells us the current SEQuence just ended
898 if( group == 0xfffe )
903 ElVal->SetValue("gdcm::Skipped");
907 // When the length is zero things are easy:
913 // The elements whose length is bigger than the specified upper bound
914 // are not loaded. Instead we leave a short notice of the offset of
915 // the element content and it's length.
916 if (length > MaxSizeLoadElementValue) {
917 std::ostringstream s;
918 s << "gdcm::NotLoaded.";
919 s << " Address:" << (long)ElVal->GetOffset();
920 s << " Length:" << ElVal->GetLength();
921 ElVal->SetValue(s.str());
925 // When an integer is expected, read and convert the following two or
926 // four bytes properly i.e. as an integer as opposed to a string.
928 // pour les elements de Value Multiplicity > 1
929 // on aura en fait une serie d'entiers
930 // on devrait pouvoir faire + compact (?)
932 if ( IsAnInteger(ElVal) ) {
934 std::ostringstream s;
936 if (vr == "US" || vr == "SS") {
938 NewInt = ReadInt16();
941 for (int i=1; i < nbInt; i++) {
943 NewInt = ReadInt16();
948 } else if (vr == "UL" || vr == "SL") {
950 NewInt = ReadInt32();
953 for (int i=1; i < nbInt; i++) {
955 NewInt = ReadInt32();
960 ElVal->SetValue(s.str());
964 // We need an additional byte for storing \0 that is not on disk
965 char* NewValue = (char*)malloc(length+1);
967 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
972 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
973 if ( item_read != 1 ) {
975 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
976 ElVal->SetValue("gdcm::UnRead");
979 ElVal->SetValue(NewValue);
984 * \ingroup gdcmHeader
985 * \brief Loads the element while preserving the current
986 * underlying file position indicator as opposed to
987 * to LoadElementValue that modifies it.
988 * @param ElVal Element whose value shall be loaded.
991 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
992 long PositionOnEntry = ftell(fp);
993 LoadElementValue(ElVal);
994 fseek(fp, PositionOnEntry, SEEK_SET);
998 * \ingroup gdcmHeader
999 * \brief Reads a supposed to be 16 Bits integer
1000 * \ (swaps it depending on processor endianity)
1002 * @return integer acts as a boolean
1004 guint16 gdcmHeader::ReadInt16(void) {
1007 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1008 if ( item_read != 1 ) {
1009 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1011 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1013 dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1023 * \ingroup gdcmHeader
1024 * \brief Reads a supposed to be 32 Bits integer
1025 * \ (swaps it depending on processor endianity)
1029 guint32 gdcmHeader::ReadInt32(void) {
1032 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1033 if ( item_read != 1 ) {
1034 //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1036 // dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1038 dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");
1048 * \ingroup gdcmHeader
1053 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1055 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1057 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1058 "failed to Locate gdcmElValue");
1059 return (gdcmElValue*)0;
1065 * \ingroup gdcmHeader
1066 * \brief Build a new Element Value from all the low level arguments.
1067 * Check for existence of dictionary entry, and build
1068 * a default one when absent.
1069 * @param Group group of the underlying DictEntry
1070 * @param Elem element of the underlying DictEntry
1072 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1073 // Find out if the tag we encountered is in the dictionaries:
1074 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1076 NewTag = new gdcmDictEntry(Group, Elem);
1078 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1080 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1081 "failed to allocate gdcmElValue");
1082 return (gdcmElValue*)0;
1088 * \ingroup gdcmHeader
1093 * \return integer acts as a boolean
1095 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value,
1096 guint16 Group, guint16 Elem ) {
1098 // TODO : FIXME JPRx
1100 // on (je) cree une Elvalue ne contenant pas de valeur
1101 // on l'ajoute au ElValSet
1102 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1103 // --> devrait pouvoir etre fait + simplement ???
1105 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1106 PubElValSet.Add(nvElValue);
1107 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1113 * \ingroup gdcmHeader
1114 * \brief Modify (or Creates if not found) an element
1115 * @param Value new value
1118 * \return integer acts as a boolean
1121 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1123 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1124 PubElValSet.Add(nvElValue);
1125 std::string v = Value;
1126 PubElValSet.SetElValueByNumber(v, Group, Elem);
1132 * \ingroup gdcmHeader
1133 * \brief Set a new value if the invoked element exists
1137 * \return integer acts as a boolean
1139 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1141 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1142 std::string v = Value;
1143 PubElValSet.SetElValueByNumber(v, Group, Elem);
1149 * \ingroup gdcmHeader
1150 * \brief Checks if a given ElValue (group,number)
1151 * \ exists in the Public ElValSet
1154 * @return integer acts as a boolean
1157 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1158 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1162 * \ingroup gdcmHeader
1163 * \brief Build a new Element Value from all the low level arguments.
1164 * Check for existence of dictionary entry, and build
1165 * a default one when absent.
1166 * @param Name Name of the underlying DictEntry
1168 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1170 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1172 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1174 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1176 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1177 "failed to allocate gdcmElValue");
1178 return (gdcmElValue*)0;
1184 * \ingroup gdcmHeader
1185 * \brief Read the next tag but WITHOUT loading it's value
1186 * @return On succes the newly created ElValue, NULL on failure.
1188 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1191 gdcmElValue * NewElVal;
1197 // We reached the EOF (or an error occured) and header parsing
1198 // has to be considered as finished.
1199 return (gdcmElValue *)0;
1201 NewElVal = NewElValueByNumber(g, n);
1203 FindLength(NewElVal);
1206 return (gdcmElValue *)0;
1208 NewElVal->SetOffset(ftell(fp));
1209 //if ( (g==0x7fe0) && (n==0x0010) )
1214 * \ingroup gdcmHeader
1215 * \brief Apply some heuristics to predict wether the considered
1216 * element value contains/represents an integer or not.
1217 * @param ElVal The element value on which to apply the predicate.
1218 * @return The result of the heuristical predicate.
1220 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1221 guint16 group = ElVal->GetGroup();
1222 guint16 element = ElVal->GetElement();
1223 std::string vr = ElVal->GetVR();
1224 guint32 length = ElVal->GetLength();
1226 // When we have some semantics on the element we just read, and if we
1227 // a priori know we are dealing with an integer, then we shall be
1228 // able to swap it's element value properly.
1229 if ( element == 0 ) { // This is the group length of the group
1233 dbg.Error("gdcmHeader::IsAnInteger",
1234 "Erroneous Group Length element length.");
1237 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1244 * \ingroup gdcmHeader
1245 * \brief Recover the offset (from the beginning of the file) of the pixels.
1247 size_t gdcmHeader::GetPixelOffset(void) {
1248 // If this file complies with the norm we should encounter the
1249 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1250 // the group that contains the pixel data (hence the "Pixel Data"
1251 // is found by indirection through the "Image Location").
1252 // Inside the group pointed by "Image Location" the searched element
1253 // is conventionally the element 0x0010 (when the norm is respected).
1254 // When the "Image Location" is absent we default to group 0x7fe0.
1257 std::string ImageLocation = GetPubElValByName("Image Location");
1258 if ( ImageLocation == GDCM_UNFOUND ) {
1261 grPixel = (guint16) atoi( ImageLocation.c_str() );
1263 if (grPixel != 0x7fe0)
1264 // This is a kludge for old dirty Philips imager.
1269 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1272 return PixelElement->GetOffset();
1278 * \ingroup gdcmHeader
1279 * \brief Searches both the public and the shadow dictionary (when they
1280 * exist) for the presence of the DictEntry with given
1281 * group and element. The public dictionary has precedence on the
1283 * @param group group of the searched DictEntry
1284 * @param element element of the searched DictEntry
1285 * @return Corresponding DictEntry when it exists, NULL otherwise.
1287 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1289 gdcmDictEntry * found = (gdcmDictEntry*)0;
1290 if (!RefPubDict && !RefShaDict) {
1291 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1292 "we SHOULD have a default dictionary");
1295 found = RefPubDict->GetTagByNumber(group, element);
1300 found = RefShaDict->GetTagByNumber(group, element);
1308 * \ingroup gdcmHeader
1309 * \brief Searches both the public and the shadow dictionary (when they
1310 * exist) for the presence of the DictEntry with given name.
1311 * The public dictionary has precedence on the shadow one.
1312 * @param Name name of the searched DictEntry
1313 * @return Corresponding DictEntry when it exists, NULL otherwise.
1315 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1316 gdcmDictEntry * found = (gdcmDictEntry*)0;
1317 if (!RefPubDict && !RefShaDict) {
1318 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1319 "we SHOULD have a default dictionary");
1322 found = RefPubDict->GetTagByName(Name);
1327 found = RefShaDict->GetTagByName(Name);
1335 * \ingroup gdcmHeader
1336 * \brief Searches within the public dictionary for element value of
1338 * @param group Group of the researched tag.
1339 * @param element Element of the researched tag.
1340 * @return Corresponding element value when it exists, and the string
1341 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1343 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1344 return PubElValSet.GetElValueByNumber(group, element);
1348 * \ingroup gdcmHeader
1349 * \brief Searches within the public dictionary for element value
1350 * representation of a given tag.
1352 * Obtaining the VR (Value Representation) might be needed by caller
1353 * to convert the string typed content to caller's native type
1354 * (think of C++ vs Python). The VR is actually of a higher level
1355 * of semantics than just the native C++ type.
1356 * @param group Group of the researched tag.
1357 * @param element Element of the researched tag.
1358 * @return Corresponding element value representation when it exists,
1359 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1361 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1362 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1364 return GDCM_UNFOUND;
1365 return elem->GetVR();
1369 * \ingroup gdcmHeader
1370 * \brief Searches within the public dictionary for element value of
1372 * @param TagName name of the researched element.
1373 * @return Corresponding element value when it exists, and the string
1374 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1376 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1377 return PubElValSet.GetElValueByName(TagName);
1381 * \ingroup gdcmHeader
1382 * \brief Searches within the elements parsed with the public dictionary for
1383 * the element value representation of a given tag.
1385 * Obtaining the VR (Value Representation) might be needed by caller
1386 * to convert the string typed content to caller's native type
1387 * (think of C++ vs Python). The VR is actually of a higher level
1388 * of semantics than just the native C++ type.
1389 * @param TagName name of the researched element.
1390 * @return Corresponding element value representation when it exists,
1391 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1393 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1394 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1396 return GDCM_UNFOUND;
1397 return elem->GetVR();
1401 * \ingroup gdcmHeader
1402 * \brief Searches within elements parsed with the SHADOW dictionary
1403 * for the element value of a given tag.
1404 * @param group Group of the researched tag.
1405 * @param element Element of the researched tag.
1406 * @return Corresponding element value representation when it exists,
1407 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1409 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1410 return ShaElValSet.GetElValueByNumber(group, element);
1414 * \ingroup gdcmHeader
1415 * \brief Searches within the elements parsed with the SHADOW dictionary
1416 * for the element value representation of a given tag.
1418 * Obtaining the VR (Value Representation) might be needed by caller
1419 * to convert the string typed content to caller's native type
1420 * (think of C++ vs Python). The VR is actually of a higher level
1421 * of semantics than just the native C++ type.
1422 * @param group Group of the researched tag.
1423 * @param element Element of the researched tag.
1424 * @return Corresponding element value representation when it exists,
1425 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1427 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1428 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1430 return GDCM_UNFOUND;
1431 return elem->GetVR();
1435 * \ingroup gdcmHeader
1436 * \brief Searches within the elements parsed with the shadow dictionary
1437 * for an element value of given tag.
1438 * @param TagName name of the researched element.
1439 * @return Corresponding element value when it exists, and the string
1440 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1442 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1443 return ShaElValSet.GetElValueByName(TagName);
1447 * \ingroup gdcmHeader
1448 * \brief Searches within the elements parsed with the shadow dictionary for
1449 * the element value representation of a given tag.
1451 * Obtaining the VR (Value Representation) might be needed by caller
1452 * to convert the string typed content to caller's native type
1453 * (think of C++ vs Python). The VR is actually of a higher level
1454 * of semantics than just the native C++ type.
1455 * @param TagName name of the researched element.
1456 * @return Corresponding element value representation when it exists,
1457 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1459 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1460 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1462 return GDCM_UNFOUND;
1463 return elem->GetVR();
1467 * \ingroup gdcmHeader
1468 * \brief Searches within elements parsed with the public dictionary
1469 * and then within the elements parsed with the shadow dictionary
1470 * for the element value of a given tag.
1471 * @param group Group of the researched tag.
1472 * @param element Element of the researched tag.
1473 * @return Corresponding element value representation when it exists,
1474 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1476 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1477 std::string pub = GetPubElValByNumber(group, element);
1480 return GetShaElValByNumber(group, element);
1484 * \ingroup gdcmHeader
1485 * \brief Searches within elements parsed with the public dictionary
1486 * and then within the elements parsed with the shadow dictionary
1487 * for the element value representation of a given tag.
1489 * Obtaining the VR (Value Representation) might be needed by caller
1490 * to convert the string typed content to caller's native type
1491 * (think of C++ vs Python). The VR is actually of a higher level
1492 * of semantics than just the native C++ type.
1493 * @param group Group of the researched tag.
1494 * @param element Element of the researched tag.
1495 * @return Corresponding element value representation when it exists,
1496 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1498 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1499 std::string pub = GetPubElValRepByNumber(group, element);
1502 return GetShaElValRepByNumber(group, element);
1506 * \ingroup gdcmHeader
1507 * \brief Searches within elements parsed with the public dictionary
1508 * and then within the elements parsed with the shadow dictionary
1509 * for the element value of a given tag.
1510 * @param TagName name of the researched element.
1511 * @return Corresponding element value when it exists,
1512 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1514 std::string gdcmHeader::GetElValByName(std::string TagName) {
1515 std::string pub = GetPubElValByName(TagName);
1518 return GetShaElValByName(TagName);
1522 * \ingroup gdcmHeader
1523 * \brief Searches within elements parsed with the public dictionary
1524 * and then within the elements parsed with the shadow dictionary
1525 * for the element value representation of a given tag.
1527 * Obtaining the VR (Value Representation) might be needed by caller
1528 * to convert the string typed content to caller's native type
1529 * (think of C++ vs Python). The VR is actually of a higher level
1530 * of semantics than just the native C++ type.
1531 * @param TagName name of the researched element.
1532 * @return Corresponding element value representation when it exists,
1533 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1535 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1536 std::string pub = GetPubElValRepByName(TagName);
1539 return GetShaElValRepByName(TagName);
1543 * \ingroup gdcmHeader
1544 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1545 * through it's (group, element) and modifies it's content with
1547 * @param content new value to substitute with
1548 * @param group group of the ElVal to modify
1549 * @param element element of the ElVal to modify
1551 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1554 //TODO : homogeneiser les noms : SetPubElValByNumber
1555 // qui appelle PubElValSet.SetElValueByNumber
1556 // pourquoi pas SetPubElValueByNumber ??
1559 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1563 * \ingroup gdcmHeader
1564 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1565 * through tag name and modifies it's content with the given value.
1566 * @param content new value to substitute with
1567 * @param TagName name of the tag to be modified
1569 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1570 return ( PubElValSet.SetElValueByName (content, TagName) );
1574 * \ingroup gdcmHeader
1575 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1576 * through it's (group, element) and modifies it's length with
1578 * \warning Use with extreme caution.
1579 * @param length new length to substitute with
1580 * @param group group of the ElVal to modify
1581 * @param element element of the ElVal to modify
1582 * @return 1 on success, 0 otherwise.
1585 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1587 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1591 * \ingroup gdcmHeader
1592 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1593 * through it's (group, element) and modifies it's content with
1595 * @param content new value to substitute with
1596 * @param group group of the ElVal to modify
1597 * @param element element of the ElVal to modify
1598 * @return 1 on success, 0 otherwise.
1600 int gdcmHeader::SetShaElValByNumber(std::string content,
1601 guint16 group, guint16 element) {
1602 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1606 * \ingroup gdcmHeader
1607 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1608 * through tag name and modifies it's content with the given value.
1609 * @param content new value to substitute with
1610 * @param ShadowTagName name of the tag to be modified
1612 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1613 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1617 * \ingroup gdcmHeader
1618 * \brief Parses the header of the file but WITHOUT loading element values.
1620 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1621 gdcmElValue * newElValue = (gdcmElValue *)0;
1625 while ( (newElValue = ReadNextElement()) ) {
1626 SkipElementValue(newElValue);
1627 PubElValSet.Add(newElValue);
1632 * \ingroup gdcmHeader
1633 * \brief This predicate, based on hopefully reasonnable heuristics,
1634 * decides whether or not the current gdcmHeader was properly parsed
1635 * and contains the mandatory information for being considered as
1636 * a well formed and usable image.
1637 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1640 bool gdcmHeader::IsReadable(void) {
1641 if ( GetElValByName("Image Dimensions") != GDCM_UNFOUND
1642 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1645 if ( GetElValByName("Bits Allocated") == GDCM_UNFOUND )
1647 if ( GetElValByName("Bits Stored") == GDCM_UNFOUND )
1649 if ( GetElValByName("High Bit") == GDCM_UNFOUND )
1651 if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1657 * \ingroup gdcmHeader
1658 * \brief Small utility function that creates a new manually crafted
1659 * (as opposed as read from the file) gdcmElValue with user
1660 * specified name and adds it to the public tag hash table.
1661 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1662 * @param NewTagName The name to be given to this new tag.
1663 * @param VR The Value Representation to be given to this new tag.
1664 * @ return The newly hand crafted Element Value.
1666 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName,
1668 gdcmElValue* NewElVal = (gdcmElValue*)0;
1669 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1670 guint32 FreeElem = 0;
1671 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1673 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1674 if (FreeElem == UINT32_MAX) {
1675 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1676 "Group 0xffff in Public Dict is full");
1677 return (gdcmElValue*)0;
1679 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1680 VR, "GDCM", NewTagName);
1681 NewElVal = new gdcmElValue(NewEntry);
1682 PubElValSet.Add(NewElVal);
1687 * \ingroup gdcmHeader
1688 * \brief Loads the element values of all the elements present in the
1689 * public tag based hash table.
1691 void gdcmHeader::LoadElements(void) {
1693 TagElValueHT ht = PubElValSet.GetTagHt();
1694 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1695 LoadElementValue(tag->second);
1699 // Load 'non string' values
1700 std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);
1701 if( PhotometricInterpretation == "PALETTE COLOR " ){
1702 LoadElementVoidArea(0x0028,0x1200); // gray LUT
1703 LoadElementVoidArea(0x0028,0x1201); // R LUT
1704 LoadElementVoidArea(0x0028,0x1202); // G LUT
1705 LoadElementVoidArea(0x0028,0x1203); // B LUT
1707 LoadElementVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1708 LoadElementVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1709 LoadElementVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1712 // --------------------------------------------------------------
1713 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1715 // if recognition code tells us we deal with a LibIDO image
1716 // we switch lineNumber and columnNumber
1718 std::string RecCode;
1719 RecCode = GetPubElValByNumber(0x0008, 0x0010);
1720 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1721 RecCode == "CANRME_AILIBOD1_1." ) {
1722 filetype = ACR_LIBIDO;
1723 std::string rows = GetPubElValByNumber(0x0028, 0x0010);
1724 std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1725 SetPubElValByNumber(columns, 0x0028, 0x0010);
1726 SetPubElValByNumber(rows , 0x0028, 0x0011);
1728 // ----------------- End of Special Patch ----------------
1732 * \ingroup gdcmHeader
1736 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1737 PubElValSet.Print(os);
1741 * \ingroup gdcmHeader
1745 void gdcmHeader::PrintPubDict(std::ostream & os) {
1746 RefPubDict->Print(os);
1750 * \ingroup gdcmHeader
1754 int gdcmHeader::Write(FILE * fp, FileType type) {
1755 return PubElValSet.Write(fp, type);
1759 // ------------------------ 'non string' elements related functions
1763 * \ingroup gdcmHeader
1764 * \brief Loads (from disk) the element content
1765 * when a string is not suitable
1767 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1768 gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1771 size_t o =(size_t)Element->GetOffset();
1772 fseek(fp, o, SEEK_SET);
1773 int l=Element->GetLength();
1774 void * a = malloc(l);
1776 std::cout << "Big Broblem (LoadElementVoidArea, malloc) "
1777 << std::hex << Group << " " << Elem << std::endl;
1780 int res = PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1781 // TODO check the result
1782 size_t l2 = fread(a, 1, l ,fp);
1784 std::cout << "Big Broblem (LoadElementVoidArea, fread) "
1785 << std::hex << Group << " " << Elem << std::endl;
1792 * \ingroup gdcmHeader
1793 * \brief Gets (from Header) the offset of a 'non string' element value
1794 * \ (LoadElementValue has already be executed)
1797 * @return File Offset of the Element Value
1799 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1800 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1802 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1803 "failed to Locate gdcmElValue");
1806 return elValue->GetOffset();
1810 * \ingroup gdcmHeader
1811 * \brief Gets (from Header) a 'non string' element value
1812 * \ (LoadElementValue has already be executed)
1815 * @return Pointer to the 'non string' area
1818 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1819 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1821 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1822 "failed to Locate gdcmElValue");
1825 return elValue->GetVoidArea();
1830 // =============================================================================
1831 // Heuristics based accessors
1832 //==============================================================================
1835 // TODO : move to an other file.
1839 * \ingroup gdcmHeader
1840 * \brief Retrieve the number of columns of image.
1841 * @return The encountered size when found, 0 by default.
1843 int gdcmHeader::GetXSize(void) {
1844 // We cannot check for "Columns" because the "Columns" tag is present
1845 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1846 std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1847 if (StrSize == GDCM_UNFOUND)
1849 return atoi(StrSize.c_str());
1853 * \ingroup gdcmHeader
1854 * \brief Retrieve the number of lines of image.
1855 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1856 * @return The encountered size when found, 1 by default.
1858 int gdcmHeader::GetYSize(void) {
1859 // We cannot check for "Rows" because the "Rows" tag is present
1860 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1861 std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1862 if (StrSize != GDCM_UNFOUND)
1863 return atoi(StrSize.c_str());
1867 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1868 // hence be a signal (1d image). So we default to 1:
1873 * \ingroup gdcmHeader
1874 * \brief Retrieve the number of planes of volume or the number
1875 * of frames of a multiframe.
1876 * \warning When present we consider the "Number of Frames" as the third
1877 * dimension. When absent we consider the third dimension as
1878 * being the "Planes" tag content.
1879 * @return The encountered size when found, 1 by default.
1881 int gdcmHeader::GetZSize(void) {
1882 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1883 // as the third dimension.
1884 std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
1885 if (StrSize != GDCM_UNFOUND)
1886 return atoi(StrSize.c_str());
1888 // We then consider the "Planes" entry as the third dimension [we
1889 // cannot retrieve by name since "Planes tag is present both in
1890 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1891 StrSize = GetPubElValByNumber(0x0028,0x0012);
1892 if (StrSize != GDCM_UNFOUND)
1893 return atoi(StrSize.c_str());
1898 * \ingroup gdcmHeader
1899 * \brief Retrieve the number of Bits Stored
1900 * (as opposite to number of Bits Allocated)
1902 * @return The encountered number of Bits Stored, 0 by default.
1904 int gdcmHeader::GetBitsStored(void) {
1905 std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
1906 if (StrSize == GDCM_UNFOUND)
1908 return atoi(StrSize.c_str());
1913 * \ingroup gdcmHeader
1914 * \brief Retrieve the number of Samples Per Pixel
1915 * (1 : gray level, 3 : RGB)
1917 * @return The encountered number of Samples Per Pixel, 1 by default.
1919 int gdcmHeader::GetSamplesPerPixel(void) {
1920 std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
1921 if (StrSize == GDCM_UNFOUND)
1922 return 1; // Well, it's supposed to be mandatory ...
1923 return atoi(StrSize.c_str());
1927 * \ingroup gdcmHeader
1928 * \brief Retrieve the Planar Configuration for RGB images
1929 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
1931 * @return The encountered Planar Configuration, 0 by default.
1933 int gdcmHeader::GetPlanarConfiguration(void) {
1934 std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
1935 if (StrSize == GDCM_UNFOUND)
1937 return atoi(StrSize.c_str());
1941 * \ingroup gdcmHeader
1942 * \brief Return the size (in bytes) of a single pixel of data.
1943 * @return The size in bytes of a single pixel of data.
1946 int gdcmHeader::GetPixelSize(void) {
1947 std::string PixelType = GetPixelType();
1948 if (PixelType == "8U" || PixelType == "8S")
1950 if (PixelType == "16U" || PixelType == "16S")
1952 if (PixelType == "32U" || PixelType == "32S")
1954 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
1959 * \ingroup gdcmHeader
1960 * \brief Build the Pixel Type of the image.
1961 * Possible values are:
1962 * - 8U unsigned 8 bit,
1963 * - 8S signed 8 bit,
1964 * - 16U unsigned 16 bit,
1965 * - 16S signed 16 bit,
1966 * - 32U unsigned 32 bit,
1967 * - 32S signed 32 bit,
1968 * \warning 12 bit images appear as 16 bit.
1971 std::string gdcmHeader::GetPixelType(void) {
1972 std::string BitsAlloc;
1973 BitsAlloc = GetElValByName("Bits Allocated");
1974 if (BitsAlloc == GDCM_UNFOUND) {
1975 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
1976 BitsAlloc = std::string("16");
1978 if (BitsAlloc == "12")
1979 BitsAlloc = std::string("16");
1982 Signed = GetElValByName("Pixel Representation");
1983 if (Signed == GDCM_UNFOUND) {
1984 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
1985 BitsAlloc = std::string("0");
1988 Signed = std::string("U");
1990 Signed = std::string("S");
1992 return( BitsAlloc + Signed);
1996 * \ingroup gdcmHeader
1997 * \brief gets the info from 0002,0010 : Transfert Syntax
1999 * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
2001 std::string gdcmHeader::GetTransferSyntaxName(void) {
2002 std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
2003 if (TransfertSyntax == GDCM_UNFOUND) {
2004 dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
2005 return "Uncompressed ACR-NEMA";
2007 // we do it only when we need it
2008 gdcmTS * ts = gdcmGlobal::GetTS();
2009 std::string tsName=ts->GetValue(TransfertSyntax);
2010 //delete ts; // Seg Fault when deleted ?!
2014 // -------------------------------- Lookup Table related functions ------------
2017 * \ingroup gdcmHeader
2018 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2020 * @return Lookup Table Length
2021 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2024 int gdcmHeader::GetLUTLength(void) {
2025 std::vector<std::string> tokens;
2029 // Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2030 std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2031 if (LutDescriptionR == GDCM_UNFOUND)
2033 std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2034 if (LutDescriptionG == GDCM_UNFOUND)
2036 std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2037 if (LutDescriptionB == GDCM_UNFOUND)
2039 if( (LutDescriptionR != LutDescriptionG) || (LutDescriptionR != LutDescriptionB) ) {
2040 dbg.Verbose(0, "gdcmHeader::GetLUTLength: The CLUT R,G,B are not equal");
2043 std::cout << "Lut Description " << LutDescriptionR <<std::endl;
2044 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2045 Tokenize (LutDescriptionR, tokens, "\\");
2046 LutLength=atoi(tokens[0].c_str());
2047 //LutDepth=atoi(tokens[1].c_str());
2048 //LutNbits=atoi(tokens[2].c_str());
2054 * \ingroup gdcmHeader
2055 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2057 * @return Lookup Table nBit
2058 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2061 int gdcmHeader::GetLUTNbits(void) {
2062 std::vector<std::string> tokens;
2066 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2067 // Consistency already checked in GetLUTLength
2068 std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2069 if (LutDescription == GDCM_UNFOUND)
2071 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2072 Tokenize (LutDescription, tokens, "\\");
2073 //LutLength=atoi(tokens[0].c_str());
2074 //LutDepth=atoi(tokens[1].c_str());
2075 LutNbits=atoi(tokens[2].c_str());
2082 * \ingroup gdcmHeader
2083 * \brief gets the info from 0028,1201 : Lookup Table Red
2085 * @return Lookup Table Red
2086 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2088 void * gdcmHeader::GetLUTRed(void) {
2089 return GetPubElValVoidAreaByNumber(0x0028,0x1201);
2093 * \ingroup gdcmHeader
2094 * \brief gets the info from 0028,1202 : Lookup Table Green
2096 * @return Lookup Table Red
2097 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2099 void * gdcmHeader::GetLUTGreen(void) {
2100 return GetPubElValVoidAreaByNumber(0x0028,0x1202);
2104 * \ingroup gdcmHeader
2105 * \brief gets the info from 0028,1202 : Lookup Table Blue
2107 * @return Lookup Table Blue
2108 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2110 void * gdcmHeader::GetLUTBlue(void) {
2111 return GetPubElValVoidAreaByNumber(0x0028,0x1203);
2115 * \ingroup gdcmHeader
2117 * @return Lookup Table RGB
2118 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2119 * \ and (0028,1201),(0028,1202),(0028,1202) are found
2120 * \warning : hazardous ! Use better GetPubElValVoidAreaByNumber
2122 void * gdcmHeader::GetLUTRGB(void) {
2123 // Not so easy : see
2124 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2125 // and OT-PAL-8-face.dcm
2127 if (GetPubElValByNumber(0x0028,0x0004) == GDCM_UNFOUND) {
2128 dbg.Verbose(0, "gdcmHeader::GetLUTRGB: unfound Photometric Interpretation");
2131 void * LutR,*LutG,*LutB;
2134 // Maybe, some day we get an image
2135 // that respects the definition ...
2136 // Let's consider no ones does.
2141 int nBits=GetLUTNbits();
2143 // a virer quand on aura trouve UNE image
2144 // qui correspond VRAIMENT à la definition !
2145 std::cout << "l " << l << " nBits " << nBits;
2149 LutR =GetPubElValVoidAreaByNumber(0x0028,0x1201);
2150 LutG =GetPubElValVoidAreaByNumber(0x0028,0x1202);
2151 LutB =GetPubElValVoidAreaByNumber(0x0028,0x1203);
2153 // Warning : Any value for nBits as to be considered as 8
2154 // Any value for Length as to be considered as 256
2157 // Just wait before removing the following code
2160 guint16 * LUTRGB, *rgb;
2161 LUTRGB = rgb = (guint16 *) malloc(3*l*sizeof( guint16));
2162 guint16 * r = (guint16 *)LutR;
2163 guint16 * g = (guint16 *)LutG;
2164 guint16 * b = (guint16 *)LutB;
2165 for(int i=0;i<l;i++) {
2173 */ { // we assume it's always 8 Bits
2174 l=256; // we assume ...
2175 unsigned char * LUTRGB, *rgb;
2176 LUTRGB = rgb = (unsigned char *) malloc(3*l*sizeof( char));
2177 unsigned char * r = (unsigned char *)LutR;
2178 unsigned char * g = (unsigned char *)LutG;
2179 unsigned char * b = (unsigned char *)LutB;
2180 for(int i=0;i<l;i++) {
2181 //std::cout << "lut16 " << i << " : " << *r << " " << *g << " " << *b
2183 printf("lut 8 %d : %d %d %d \n",i,*r,*g,*b);
2188 free(LutR); free(LutB); free(LutG);
2192 /* Sorry for the comments. The code will be moved in a fonction
2194 std::string x=GetPubElValByNumber(0x0028,0x1201);
2195 unsigned short int * lutR = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2196 unsigned short int * lutG = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2197 unsigned short int * lutB = (unsigned short int *)malloc((size_t)200*sizeof(short int));
2199 std::vector<std::string> tokens;
2200 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2201 Tokenize ((const std::string)x, tokens, "\\");
2202 for (unsigned int i=0; i<tokens.size();i++) {
2203 lutR[i] = atoi(tokens[i].c_str());
2204 printf("%d (%x)\n",lutR[i],lutR[i]);
2207 std::string y=GetPubElValByNumber(0x0028,0x1202);
2208 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2209 Tokenize ((const std::string)y, tokens, "\\");
2210 for (unsigned int i=0; i<tokens.size();i++) {
2211 lutG[i] = atoi(tokens[i].c_str());
2214 std::string z=GetPubElValByNumber(0x0028,0x1203);
2215 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2216 Tokenize ((const std::string)z, tokens, "\\");
2217 for (unsigned int i=0; i<tokens.size();i++) {
2218 lutB[i] = atoi(tokens[i].c_str());
2220 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2221 Tokenize ((const std::string)x, tokens, "\\");
2222 for (unsigned int i=0; i<tokens.size();i++) {
2223 lutB[i] = atoi(tokens[i].c_str());
2228 //int lgth=GetLUTLength();
2229 //cout << "lgth " << lgth << std::endl;;
2230 //for (int j=0;j<lgth;j++){
2231 //printf ("%d : %d (%x) %d (%x) %d (%x)\n",j,lutR[j],lutR[j],lutG[j],lutG[j],lutB[j],lutB[j]);