1 // $Header: /cvs/public/gdcm/src/Attic/gdcmHeader.cxx,v 1.107 2003/11/03 10:49:31 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)");
78 fread(&zero, (size_t)2, (size_t)1, fp);
80 //ACR -- or DICOM with no Preamble
81 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
84 fseek(fp, 126L, SEEK_CUR);
86 fread(dicm, (size_t)4, (size_t)1, fp);
87 if( memcmp(dicm, "DICM", 4) == 0 )
90 dbg.Verbose(0, "gdcmHeader::gdcmHeader not DICOM/ACR", filename.c_str());
93 dbg.Verbose(0, "gdcmHeader::gdcmHeader cannot open file", filename.c_str());
101 * @return TRUE if the close was successfull
103 bool gdcmHeader::CloseFile(void) {
104 int closed = fclose(fp);
112 * \ingroup gdcmHeader
113 * \brief Canonical destructor.
115 gdcmHeader::~gdcmHeader (void) {
116 dicom_vr = (gdcmVR*)0;
117 Dicts = (gdcmDictSet*)0;
118 RefPubDict = (gdcmDict*)0;
119 RefShaDict = (gdcmDict*)0;
125 // ---> Warning : This fourth field is NOT part
126 // of the 'official' Dicom Dictionnary
127 // and should NOT be used.
128 // (Not defined for all the groups
129 // may be removed in a future release)
132 // META Meta Information
144 // NMI Nuclear Medicine
146 // BFS Basic Film Session
147 // BFB Basic Film Box
148 // BIB Basic Image Box
164 * \ingroup gdcmHeader
165 * \brief Discover what the swap code is (among little endian, big endian,
166 * bad little endian, bad big endian).
169 void gdcmHeader::CheckSwap()
171 // The only guaranted way of finding the swap code is to find a
172 // group tag since we know it's length has to be of four bytes i.e.
173 // 0x00000004. Finding the swap code in then straigthforward. Trouble
174 // occurs when we can't find such group...
176 guint32 x=4; // x : for ntohs
177 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
181 char deb[HEADER_LENGTH_TO_READ];
183 // First, compare HostByteOrder and NetworkByteOrder in order to
184 // determine if we shall need to swap bytes (i.e. the Endian type).
190 // The easiest case is the one of a DICOM header, since it possesses a
191 // file preamble where it suffice to look for the string "DICM".
192 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
195 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
196 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "looks like DICOM Version3");
197 // Next, determine the value representation (VR). Let's skip to the
198 // first element (0002, 0000) and check there if we find "UL"
199 // - or "OB" if the 1st one is (0002,0001) -,
200 // in which case we (almost) know it is explicit VR.
201 // WARNING: if it happens to be implicit VR then what we will read
202 // is the length of the group. If this ascii representation of this
203 // length happens to be "UL" then we shall believe it is explicit VR.
204 // FIXME: in order to fix the above warning, we could read the next
205 // element value (or a couple of elements values) in order to make
206 // sure we are not commiting a big mistake.
208 // * the 128 bytes of File Preamble (often padded with zeroes),
209 // * the 4 bytes of "DICM" string,
210 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
211 // i.e. a total of 136 bytes.
214 // Use gdcmHeader::dicom_vr to test all the possibilities
215 // instead of just checking for UL, OB and UI !?
216 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
217 (memcmp(entCur, "OB", (size_t)2) == 0) ||
218 (memcmp(entCur, "UI", (size_t)2) == 0) )
220 filetype = ExplicitVR;
221 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
222 "explicit Value Representation");
224 filetype = ImplicitVR;
225 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
226 "not an explicit Value Representation");
230 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
231 "HostByteOrder != NetworkByteOrder");
234 dbg.Verbose(1, "gdcmHeader::CheckSwap:",
235 "HostByteOrder = NetworkByteOrder");
238 // Position the file position indicator at first tag (i.e.
239 // after the file preamble and the "DICM" string).
241 fseek (fp, 132L, SEEK_SET);
245 // Alas, this is not a DicomV3 file and whatever happens there is no file
246 // preamble. We can reset the file position indicator to where the data
247 // is (i.e. the beginning of the file).
248 dbg.Verbose(1, "gdcmHeader::CheckSwap:", "not a DICOM Version3 file");
251 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
252 // By clean we mean that the length of the first tag is written down.
253 // If this is the case and since the length of the first group HAS to be
254 // four (bytes), then determining the proper swap code is straightforward.
257 // We assume the array of char we are considering contains the binary
258 // representation of a 32 bits integer. Hence the following dirty
260 s = *((guint32 *)(entCur));
280 dbg.Verbose(0, "gdcmHeader::CheckSwap:",
281 "ACR/NEMA unfound swap info (time to raise bets)");
284 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
285 // It is time for despaired wild guesses. So, let's assume this file
286 // happens to be 'dirty' ACR/NEMA, i.e. the length of the group is
287 // not present. Then the only info we have is the net2host one.
297 * \ingroup gdcmHeader
300 void gdcmHeader::SwitchSwapToBigEndian(void) {
301 dbg.Verbose(1, "gdcmHeader::SwitchSwapToBigEndian",
302 "Switching to BigEndian mode.");
320 * \ingroup gdcmHeader
321 * \brief Find the value representation of the current tag.
324 void gdcmHeader::FindVR( gdcmElValue *ElVal) {
325 if (filetype != ExplicitVR)
331 char msg[100]; // for sprintf. Sorry
333 long PositionOnEntry = ftell(fp);
334 // Warning: we believe this is explicit VR (Value Representation) because
335 // we used a heuristic that found "UL" in the first tag. Alas this
336 // doesn't guarantee that all the tags will be in explicit VR. In some
337 // cases (see e-film filtered files) one finds implicit VR tags mixed
338 // within an explicit VR file. Hence we make sure the present tag
339 // is in explicit VR and try to fix things if it happens not to be
341 bool RealExplicit = true;
343 lgrLue=fread (&VR, (size_t)2,(size_t)1, fp);
345 vr = std::string(VR);
347 // Assume we are reading a falsely explicit VR file i.e. we reached
348 // a tag where we expect reading a VR but are in fact we read the
349 // first to bytes of the length. Then we will interogate (through find)
350 // the dicom_vr dictionary with oddities like "\004\0" which crashes
351 // both GCC and VC++ implementations of the STL map. Hence when the
352 // expected VR read happens to be non-ascii characters we consider
353 // we hit falsely explicit VR tag.
355 if ( (!isalpha(VR[0])) && (!isalpha(VR[1])) )
356 RealExplicit = false;
358 // CLEANME searching the dicom_vr at each occurence is expensive.
359 // PostPone this test in an optional integrity check at the end
360 // of parsing or only in debug mode.
361 if ( RealExplicit && !dicom_vr->Count(vr) )
364 if ( RealExplicit ) {
365 if ( ElVal->IsVrUnknown() ) {
366 // When not a dictionary entry, we can safely overwrite the vr.
370 if ( ElVal->GetVR() == vr ) {
371 // The vr we just read and the dictionary agree. Nothing to do.
374 // The vr present in the file and the dictionary disagree. We assume
375 // the file writer knew best and use the vr of the file. Since it would
376 // be unwise to overwrite the vr of a dictionary (since it would
377 // compromise it's next user), we need to clone the actual DictEntry
378 // and change the vr for the read one.
379 gdcmDictEntry* NewTag = new gdcmDictEntry(ElVal->GetGroup(),
384 ElVal->SetDictEntry(NewTag);
388 // We thought this was explicit VR, but we end up with an
389 // implicit VR tag. Let's backtrack.
391 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
392 ElVal->GetGroup(),ElVal->GetElement());
393 dbg.Verbose(1, "gdcmHeader::FindVR: ",msg);
395 fseek(fp, PositionOnEntry, SEEK_SET);
396 // When this element is known in the dictionary we shall use, e.g. for
397 // the semantics (see the usage of IsAnInteger), the vr proposed by the
398 // dictionary entry. Still we have to flag the element as implicit since
399 // we know now our assumption on expliciteness is not furfilled.
401 if ( ElVal->IsVrUnknown() )
402 ElVal->SetVR("Implicit");
403 ElVal->SetImplicitVr();
407 * \ingroup gdcmHeader
408 * \brief Determines if the Transfer Syntax was already encountered
409 * and if it corresponds to a ImplicitVRLittleEndian one.
411 * @return True when ImplicitVRLittleEndian found. False in all other cases.
413 bool gdcmHeader::IsImplicitVRLittleEndianTransferSyntax(void) {
414 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
417 LoadElementValueSafe(Element);
418 std::string Transfer = Element->GetValue();
419 if ( Transfer == "1.2.840.10008.1.2" )
425 * \ingroup gdcmHeader
426 * \brief Determines if the Transfer Syntax was already encountered
427 * and if it corresponds to a ExplicitVRLittleEndian one.
429 * @return True when ExplicitVRLittleEndian found. False in all other cases.
431 bool gdcmHeader::IsExplicitVRLittleEndianTransferSyntax(void) {
432 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
435 LoadElementValueSafe(Element);
436 std::string Transfer = Element->GetValue();
437 if ( Transfer == "1.2.840.10008.1.2.1" )
443 * \ingroup gdcmHeader
444 * \brief Determines if the Transfer Syntax was already encountered
445 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
447 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
449 bool gdcmHeader::IsDeflatedExplicitVRLittleEndianTransferSyntax(void) {
450 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
453 LoadElementValueSafe(Element);
454 std::string Transfer = Element->GetValue();
455 if ( Transfer == "1.2.840.10008.1.2.1.99" )
461 * \ingroup gdcmHeader
462 * \brief Determines if the Transfer Syntax was already encountered
463 * and if it corresponds to a Explicit VR Big Endian one.
465 * @return True when big endian found. False in all other cases.
467 bool gdcmHeader::IsExplicitVRBigEndianTransferSyntax(void) {
468 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
471 LoadElementValueSafe(Element);
472 std::string Transfer = Element->GetValue();
473 if ( Transfer == "1.2.840.10008.1.2.2" ) //1.2.2 ??? A verifier !
479 * \ingroup gdcmHeader
480 * \brief Determines if the Transfer Syntax was already encountered
481 * and if it corresponds to a JPEGBaseLineProcess1 one.
483 * @return True when JPEGBaseLineProcess1found. False in all other cases.
485 bool gdcmHeader::IsJPEGBaseLineProcess1TransferSyntax(void) {
486 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
489 LoadElementValueSafe(Element);
490 std::string Transfer = Element->GetValue();
491 if ( Transfer == "1.2.840.10008.1.2.4.50" )
497 * \ingroup gdcmHeader
502 bool gdcmHeader::IsJPEGLossless(void) {
503 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
504 // faire qq chose d'intelligent a la place de ça
507 LoadElementValueSafe(Element);
508 const char * Transfert = Element->GetValue().c_str();
509 if ( memcmp(Transfert+strlen(Transfert)-2 ,"70",2)==0) return true;
510 if ( memcmp(Transfert+strlen(Transfert)-2 ,"55",2)==0) return true;
511 if (Element->GetValue() == "1.2.840.10008.1.2.4.57") return true;
518 * \ingroup gdcmHeader
519 * \brief Determines if the Transfer Syntax was already encountered
520 * and if it corresponds to a JPEGExtendedProcess2-4 one.
522 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
524 bool gdcmHeader::IsJPEGExtendedProcess2_4TransferSyntax(void) {
525 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
528 LoadElementValueSafe(Element);
529 std::string Transfer = Element->GetValue();
530 if ( Transfer == "1.2.840.10008.1.2.4.51" )
536 * \ingroup gdcmHeader
537 * \brief Determines if the Transfer Syntax was already encountered
538 * and if it corresponds to a JPEGExtendeProcess3-5 one.
540 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
542 bool gdcmHeader::IsJPEGExtendedProcess3_5TransferSyntax(void) {
543 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
546 LoadElementValueSafe(Element);
547 std::string Transfer = Element->GetValue();
548 if ( Transfer == "1.2.840.10008.1.2.4.52" )
554 * \ingroup gdcmHeader
555 * \brief Determines if the Transfer Syntax was already encountered
556 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
558 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
561 bool gdcmHeader::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void) {
562 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
565 LoadElementValueSafe(Element);
566 std::string Transfer = Element->GetValue();
567 if ( Transfer == "1.2.840.10008.1.2.4.53" )
573 * \ingroup gdcmHeader
574 * \brief Determines if the Transfer Syntax was already encountered
575 * and if it corresponds to a RLE Lossless one.
577 * @return True when RLE Lossless found. False in all
580 bool gdcmHeader::IsRLELossLessTransferSyntax(void) {
581 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
584 LoadElementValueSafe(Element);
585 std::string Transfer = Element->GetValue();
586 if ( Transfer == "1.2.840.10008.1.2.5" )
592 * \ingroup gdcmHeader
593 * \brief Determines if the Transfer Syntax was already encountered
594 * and if it corresponds to a JPEG200 one.0
596 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
599 bool gdcmHeader::IsJPEG2000(void) {
600 gdcmElValue* Element = PubElValSet.GetElementByNumber(0x0002, 0x0010);
603 LoadElementValueSafe(Element);
604 std::string Transfer = Element->GetValue();
605 if ( (Transfer == "1.2.840.10008.1.2.4.90")
606 || (Transfer == "1.2.840.10008.1.2.4.91") )
612 * \ingroup gdcmHeader
613 * \brief Predicate for dicom version 3 file.
614 * @return True when the file is a dicom version 3.
616 bool gdcmHeader::IsDicomV3(void) {
617 if ( (filetype == ExplicitVR)
618 || (filetype == ImplicitVR) )
624 * \ingroup gdcmHeader
625 * \brief When the length of an element value is obviously wrong (because
626 * the parser went Jabberwocky) one can hope improving things by
627 * applying this heuristic.
629 void gdcmHeader::FixFoundLength(gdcmElValue * ElVal, guint32 FoundLength) {
630 if ( FoundLength == 0xffffffff)
633 // Sorry for the patch!
634 // XMedCom did the trick to read some nasty GE images ...
635 else if (FoundLength == 13) {
636 // The following 'if' will be removed when there is no more
637 // images on Creatis HDs with a 13 length for Manufacturer...
638 if ( (ElVal->GetGroup() != 0x0008) || (ElVal->GetElement() != 0x0070)) {
639 // end of remove area
643 // to fix some garbage 'Leonardo' Siemens images
644 // May be commented out to avoid overhead
645 else if ( (ElVal->GetGroup() == 0x0009)
647 ( (ElVal->GetElement() == 0x1113) || (ElVal->GetElement() == 0x1114) ) )
650 ElVal->SetLength(FoundLength);
654 * \ingroup gdcmHeader
659 guint32 gdcmHeader::FindLengthOB(void) {
660 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
663 long PositionOnEntry = ftell(fp);
664 bool FoundSequenceDelimiter = false;
665 guint32 TotalLength = 0;
668 while ( ! FoundSequenceDelimiter) {
673 TotalLength += 4; // We even have to decount the group and element
675 if ( g != 0xfffe && g!=0xb00c ) /*for bogus header */ {
676 char msg[100]; // for sprintf. Sorry
677 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
678 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
682 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) /* for bogus header */
683 FoundSequenceDelimiter = true;
684 else if ( n != 0xe000 ){
685 char msg[100]; // for sprintf. Sorry
686 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
688 dbg.Verbose(1, "gdcmHeader::FindLengthOB: ",msg);
692 ItemLength = ReadInt32();
693 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
694 // the ItemLength with ReadInt32
695 SkipBytes(ItemLength);
697 fseek(fp, PositionOnEntry, SEEK_SET);
702 * \ingroup gdcmHeader
707 void gdcmHeader::FindLength (gdcmElValue * ElVal) {
708 guint16 element = ElVal->GetElement();
709 guint16 group = ElVal->GetGroup();
710 std::string vr = ElVal->GetVR();
712 if( (element == 0x0010) && (group == 0x7fe0) ) {
714 dbg.Verbose(2, "gdcmHeader::FindLength: ",
715 "we reached 7fe0 0010");
718 if ( (filetype == ExplicitVR) && ! ElVal->IsImplicitVr() ) {
719 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") ) {
721 // The following reserved two bytes (see PS 3.5-2001, section
722 // 7.1.2 Data element structure with explicit vr p27) must be
723 // skipped before proceeding on reading the length on 4 bytes.
724 fseek(fp, 2L, SEEK_CUR);
726 guint32 length32 = ReadInt32();
728 if ( (vr == "OB") && (length32 == 0xffffffff) ) {
729 ElVal->SetLength(FindLengthOB());
732 FixFoundLength(ElVal, length32);
736 // Length is encoded on 2 bytes.
737 length16 = ReadInt16();
739 // We can tell the current file is encoded in big endian (like
740 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
741 // and it's value is the one of the encoding of a big endian file.
742 // In order to deal with such big endian encoded files, we have
743 // (at least) two strategies:
744 // * when we load the "Transfer Syntax" tag with value of big endian
745 // encoding, we raise the proper flags. Then we wait for the end
746 // of the META group (0x0002) among which is "Transfer Syntax",
747 // before switching the swap code to big endian. We have to postpone
748 // the switching of the swap code since the META group is fully encoded
749 // in little endian, and big endian coding only starts at the next
750 // group. The corresponding code can be hard to analyse and adds
751 // many additional unnecessary tests for regular tags.
752 // * the second strategy consists in waiting for trouble, that shall
753 // appear when we find the first group with big endian encoding. This
754 // is easy to detect since the length of a "Group Length" tag (the
755 // ones with zero as element number) has to be of 4 (0x0004). When we
756 // encouter 1024 (0x0400) chances are the encoding changed and we
757 // found a group with big endian encoding.
758 // We shall use this second strategy. In order to make sure that we
759 // can interpret the presence of an apparently big endian encoded
760 // length of a "Group Length" without committing a big mistake, we
761 // add an additional check: we look in the already parsed elements
762 // for the presence of a "Transfer Syntax" whose value has to be "big
763 // endian encoding". When this is the case, chances are we have got our
764 // hands on a big endian encoded file: we switch the swap code to
765 // big endian and proceed...
766 if ( (element == 0x0000) && (length16 == 0x0400) ) {
767 if ( ! IsExplicitVRBigEndianTransferSyntax() ) {
768 dbg.Verbose(0, "gdcmHeader::FindLength", "not explicit VR");
773 SwitchSwapToBigEndian();
774 // Restore the unproperly loaded values i.e. the group, the element
775 // and the dictionary entry depending on them.
776 guint16 CorrectGroup = SwapShort(ElVal->GetGroup());
777 guint16 CorrectElem = SwapShort(ElVal->GetElement());
778 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
781 // This correct tag is not in the dictionary. Create a new one.
782 NewTag = new gdcmDictEntry(CorrectGroup, CorrectElem);
784 // FIXME this can create a memory leaks on the old entry that be
785 // left unreferenced.
786 ElVal->SetDictEntry(NewTag);
789 // Heuristic: well some files are really ill-formed.
790 if ( length16 == 0xffff) {
792 //dbg.Verbose(0, "gdcmHeader::FindLength",
793 // "Erroneous element length fixed.");
794 // Actually, length= 0xffff means that we deal with
795 // Unknown Sequence Length
798 FixFoundLength(ElVal, (guint32)length16);
802 // Either implicit VR or a non DICOM conformal (see not below) explicit
803 // VR that ommited the VR of (at least) this element. Farts happen.
804 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
805 // on Data elements "Implicit and Explicit VR Data Elements shall
806 // not coexist in a Data Set and Data Sets nested within it".]
807 // Length is on 4 bytes.
808 FixFoundLength(ElVal, ReadInt32());
812 * \ingroup gdcmHeader
813 * \brief Swaps back the bytes of 4-byte long integer accordingly to
815 * @return The properly swaped 32 bits integer.
817 guint32 gdcmHeader::SwapLong(guint32 a) {
822 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
823 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
827 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
831 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
834 dbg.Error(" gdcmHeader::SwapLong : unset swap code");
841 * \ingroup gdcmHeader
842 * \brief Swaps the bytes so they agree with the processor order
843 * @return The properly swaped 16 bits integer.
845 guint16 gdcmHeader::SwapShort(guint16 a) {
846 if ( (sw==4321) || (sw==2143) )
847 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
852 * \ingroup gdcmHeader
857 void gdcmHeader::SkipBytes(guint32 NBytes) {
858 //FIXME don't dump the returned value
859 (void)fseek(fp, (long)NBytes, SEEK_CUR);
863 * \ingroup gdcmHeader
868 void gdcmHeader::SkipElementValue(gdcmElValue * ElVal) {
869 SkipBytes(ElVal->GetLength());
873 * \ingroup gdcmHeader
878 void gdcmHeader::SetMaxSizeLoadElementValue(long NewSize) {
881 if ((guint32)NewSize >= (guint32)0xffffffff) {
882 MaxSizeLoadElementValue = 0xffffffff;
885 MaxSizeLoadElementValue = NewSize;
889 * \ingroup gdcmHeader
890 * \brief Loads the element content if it's length is not bigger
891 * than the value specified with
892 * gdcmHeader::SetMaxSizeLoadElementValue()
894 void gdcmHeader::LoadElementValue(gdcmElValue * ElVal) {
896 guint16 group = ElVal->GetGroup();
897 std::string vr= ElVal->GetVR();
898 guint32 length = ElVal->GetLength();
899 bool SkipLoad = false;
901 fseek(fp, (long)ElVal->GetOffset(), SEEK_SET);
903 // FIXME Sequences not treated yet !
905 // Ne faudrait-il pas au contraire trouver immediatement
906 // une maniere 'propre' de traiter les sequences (vr = SQ)
907 // car commencer par les ignorer risque de conduire a qq chose
908 // qui pourrait ne pas etre generalisable
909 // Well, I'm expecting your code !!!
914 // A sequence "contains" a set of Elements.
915 // (fffe e000) tells us an Element is beginning
916 // (fffe e00d) tells us an Element just ended
917 // (fffe e0dd) tells us the current SQuence just ended
919 if( group == 0xfffe )
924 ElVal->SetValue("gdcm::Skipped");
928 // When the length is zero things are easy:
934 // The elements whose length is bigger than the specified upper bound
935 // are not loaded. Instead we leave a short notice of the offset of
936 // the element content and it's length.
937 if (length > MaxSizeLoadElementValue) {
938 std::ostringstream s;
939 s << "gdcm::NotLoaded.";
940 s << " Address:" << (long)ElVal->GetOffset();
941 s << " Length:" << ElVal->GetLength();
942 ElVal->SetValue(s.str());
946 // When an integer is expected, read and convert the following two or
947 // four bytes properly i.e. as an integer as opposed to a string.
949 // pour les elements de Value Multiplicity > 1
950 // on aura en fait une serie d'entiers
951 // on devrait pouvoir faire + compact (?)
953 if ( IsAnInteger(ElVal) ) {
955 std::ostringstream s;
957 if (vr == "US" || vr == "SS") {
959 NewInt = ReadInt16();
962 for (int i=1; i < nbInt; i++) {
964 NewInt = ReadInt16();
969 } else if (vr == "UL" || vr == "SL") {
971 NewInt = ReadInt32();
974 for (int i=1; i < nbInt; i++) {
976 NewInt = ReadInt32();
981 ElVal->SetValue(s.str());
985 // We need an additional byte for storing \0 that is not on disk
986 char* NewValue = (char*)malloc(length+1);
988 dbg.Verbose(1, "LoadElementValue: Failed to allocate NewValue");
993 item_read = fread(NewValue, (size_t)length, (size_t)1, fp);
994 if ( item_read != 1 ) {
996 dbg.Verbose(1, "gdcmHeader::LoadElementValue","unread element value");
997 ElVal->SetValue("gdcm::UnRead");
1000 ElVal->SetValue(NewValue);
1005 * \ingroup gdcmHeader
1006 * \brief Loads the element while preserving the current
1007 * underlying file position indicator as opposed to
1008 * to LoadElementValue that modifies it.
1009 * @param ElVal Element whose value shall be loaded.
1012 void gdcmHeader::LoadElementValueSafe(gdcmElValue * ElVal) {
1013 long PositionOnEntry = ftell(fp);
1014 LoadElementValue(ElVal);
1015 fseek(fp, PositionOnEntry, SEEK_SET);
1019 * \ingroup gdcmHeader
1020 * \brief Reads a supposed to be 16 Bits integer
1021 * \ (swaps it depending on processor endianity)
1023 * @return integer acts as a boolean
1025 guint16 gdcmHeader::ReadInt16(void) {
1028 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1029 if ( item_read != 1 ) {
1030 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " Failed to read :");
1032 // dbg.Verbose(0, "gdcmHeader::ReadInt16", " End of File encountered");
1034 dbg.Verbose(0, "gdcmHeader::ReadInt16", " File Error");
1044 * \ingroup gdcmHeader
1045 * \brief Reads a supposed to be 32 Bits integer
1046 * \ (swaps it depending on processor endianity)
1050 guint32 gdcmHeader::ReadInt32(void) {
1053 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1054 if ( item_read != 1 ) {
1055 //dbg.Verbose(0, "gdcmHeader::ReadInt32", " Failed to read :");
1057 // dbg.Verbose(0, "gdcmHeader::ReadInt32", " End of File encountered");
1059 dbg.Verbose(0, "gdcmHeader::ReadInt32", " File Error");
1069 * \ingroup gdcmHeader
1074 gdcmElValue* gdcmHeader::GetElValueByNumber(guint16 Group, guint16 Elem) {
1076 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1078 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1079 "failed to Locate gdcmElValue");
1080 return (gdcmElValue*)0;
1086 * \ingroup gdcmHeader
1087 * \brief Build a new Element Value from all the low level arguments.
1088 * Check for existence of dictionary entry, and build
1089 * a default one when absent.
1090 * @param Group group of the underlying DictEntry
1091 * @param Elem element of the underlying DictEntry
1093 gdcmElValue* gdcmHeader::NewElValueByNumber(guint16 Group, guint16 Elem) {
1094 // Find out if the tag we encountered is in the dictionaries:
1095 gdcmDictEntry * NewTag = GetDictEntryByNumber(Group, Elem);
1097 NewTag = new gdcmDictEntry(Group, Elem);
1099 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1101 dbg.Verbose(1, "gdcmHeader::NewElValueByNumber",
1102 "failed to allocate gdcmElValue");
1103 return (gdcmElValue*)0;
1109 * \ingroup gdcmHeader
1114 * \return integer acts as a boolean
1116 int gdcmHeader::ReplaceOrCreateByNumber(std::string Value,
1117 guint16 Group, guint16 Elem ) {
1119 // TODO : FIXME JPRx
1121 // on (je) cree une Elvalue ne contenant pas de valeur
1122 // on l'ajoute au ElValSet
1123 // on affecte une valeur a cette ElValue a l'interieur du ElValSet
1124 // --> devrait pouvoir etre fait + simplement ???
1125 if (CheckIfExistByNumber(Group, Elem) == 0) {
1126 gdcmElValue* a =NewElValueByNumber(Group, Elem);
1131 PubElValSet.SetElValueByNumber(Value, Group, Elem);
1137 * \ingroup gdcmHeader
1138 * \brief Modify (or Creates if not found) an element
1139 * @param Value new value
1142 * \return integer acts as a boolean
1145 int gdcmHeader::ReplaceOrCreateByNumber(char* Value, guint16 Group, guint16 Elem ) {
1147 gdcmElValue* nvElValue=NewElValueByNumber(Group, Elem);
1148 PubElValSet.Add(nvElValue);
1149 std::string v = Value;
1150 PubElValSet.SetElValueByNumber(v, Group, Elem);
1156 * \ingroup gdcmHeader
1157 * \brief Set a new value if the invoked element exists
1158 * Seems to be useless !!!
1162 * \return integer acts as a boolean
1164 int gdcmHeader::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem ) {
1166 //gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1167 std::string v = Value;
1168 PubElValSet.SetElValueByNumber(v, Group, Elem);
1174 * \ingroup gdcmHeader
1175 * \brief Checks if a given ElValue (group,number)
1176 * \ exists in the Public ElValSet
1179 * @return integer acts as a boolean
1182 int gdcmHeader::CheckIfExistByNumber(guint16 Group, guint16 Elem ) {
1183 return (PubElValSet.CheckIfExistByNumber(Group, Elem));
1187 * \ingroup gdcmHeader
1188 * \brief Build a new Element Value from all the low level arguments.
1189 * Check for existence of dictionary entry, and build
1190 * a default one when absent.
1191 * @param Name Name of the underlying DictEntry
1193 gdcmElValue* gdcmHeader::NewElValueByName(std::string Name) {
1195 gdcmDictEntry * NewTag = GetDictEntryByName(Name);
1197 NewTag = new gdcmDictEntry(0xffff, 0xffff, "LO", "Unknown", Name);
1199 gdcmElValue* NewElVal = new gdcmElValue(NewTag);
1201 dbg.Verbose(1, "gdcmHeader::ObtainElValueByName",
1202 "failed to allocate gdcmElValue");
1203 return (gdcmElValue*)0;
1209 * \ingroup gdcmHeader
1210 * \brief Read the next tag but WITHOUT loading it's value
1211 * @return On succes the newly created ElValue, NULL on failure.
1213 gdcmElValue * gdcmHeader::ReadNextElement(void) {
1216 gdcmElValue * NewElVal;
1222 // We reached the EOF (or an error occured) and header parsing
1223 // has to be considered as finished.
1224 return (gdcmElValue *)0;
1226 NewElVal = NewElValueByNumber(g, n);
1228 FindLength(NewElVal);
1231 return (gdcmElValue *)0;
1233 NewElVal->SetOffset(ftell(fp));
1234 //if ( (g==0x7fe0) && (n==0x0010) )
1239 * \ingroup gdcmHeader
1240 * \brief Apply some heuristics to predict wether the considered
1241 * element value contains/represents an integer or not.
1242 * @param ElVal The element value on which to apply the predicate.
1243 * @return The result of the heuristical predicate.
1245 bool gdcmHeader::IsAnInteger(gdcmElValue * ElVal) {
1246 guint16 element = ElVal->GetElement();
1247 std::string vr = ElVal->GetVR();
1248 guint32 length = ElVal->GetLength();
1250 // When we have some semantics on the element we just read, and if we
1251 // a priori know we are dealing with an integer, then we shall be
1252 // able to swap it's element value properly.
1253 if ( element == 0 ) { // This is the group length of the group
1257 dbg.Error("gdcmHeader::IsAnInteger",
1258 "Erroneous Group Length element length.");
1261 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1268 * \ingroup gdcmHeader
1269 * \brief Recover the offset (from the beginning of the file) of the pixels.
1271 size_t gdcmHeader::GetPixelOffset(void) {
1272 // If this file complies with the norm we should encounter the
1273 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1274 // the group that contains the pixel data (hence the "Pixel Data"
1275 // is found by indirection through the "Image Location").
1276 // Inside the group pointed by "Image Location" the searched element
1277 // is conventionally the element 0x0010 (when the norm is respected).
1278 // When the "Image Location" is absent we default to group 0x7fe0.
1281 std::string ImageLocation = GetPubElValByName("Image Location");
1282 if ( ImageLocation == GDCM_UNFOUND ) {
1285 grPixel = (guint16) atoi( ImageLocation.c_str() );
1287 if (grPixel != 0x7fe0)
1288 // This is a kludge for old dirty Philips imager.
1293 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1296 return PixelElement->GetOffset();
1302 * \ingroup gdcmHeader
1303 * \brief Recover the pixel area length (in Bytes) .
1305 size_t gdcmHeader::GetPixelAreaLength(void) {
1306 // If this file complies with the norm we should encounter the
1307 // "Image Location" tag (0x0028, 0x0200). This tag contains the
1308 // the group that contains the pixel data (hence the "Pixel Data"
1309 // is found by indirection through the "Image Location").
1310 // Inside the group pointed by "Image Location" the searched element
1311 // is conventionally the element 0x0010 (when the norm is respected).
1312 // When the "Image Location" is absent we default to group 0x7fe0.
1315 std::string ImageLocation = GetPubElValByName("Image Location");
1316 if ( ImageLocation == GDCM_UNFOUND ) {
1319 grPixel = (guint16) atoi( ImageLocation.c_str() );
1321 if (grPixel != 0x7fe0)
1322 // This is a kludge for old dirty Philips imager.
1327 gdcmElValue* PixelElement = PubElValSet.GetElementByNumber(grPixel,
1330 return PixelElement->GetLength();
1336 * \ingroup gdcmHeader
1337 * \brief Searches both the public and the shadow dictionary (when they
1338 * exist) for the presence of the DictEntry with given
1339 * group and element. The public dictionary has precedence on the
1341 * @param group group of the searched DictEntry
1342 * @param element element of the searched DictEntry
1343 * @return Corresponding DictEntry when it exists, NULL otherwise.
1345 gdcmDictEntry * gdcmHeader::GetDictEntryByNumber(guint16 group,
1347 gdcmDictEntry * found = (gdcmDictEntry*)0;
1348 if (!RefPubDict && !RefShaDict) {
1349 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1350 "we SHOULD have a default dictionary");
1353 found = RefPubDict->GetTagByNumber(group, element);
1358 found = RefShaDict->GetTagByNumber(group, element);
1366 * \ingroup gdcmHeader
1367 * \brief Searches both the public and the shadow dictionary (when they
1368 * exist) for the presence of the DictEntry with given name.
1369 * The public dictionary has precedence on the shadow one.
1370 * @param Name name of the searched DictEntry
1371 * @return Corresponding DictEntry when it exists, NULL otherwise.
1373 gdcmDictEntry * gdcmHeader::GetDictEntryByName(std::string Name) {
1374 gdcmDictEntry * found = (gdcmDictEntry*)0;
1375 if (!RefPubDict && !RefShaDict) {
1376 dbg.Verbose(0, "gdcmHeader::GetDictEntry",
1377 "we SHOULD have a default dictionary");
1380 found = RefPubDict->GetTagByName(Name);
1385 found = RefShaDict->GetTagByName(Name);
1393 * \ingroup gdcmHeader
1394 * \brief Searches within the public dictionary for element value of
1396 * @param group Group of the researched tag.
1397 * @param element Element of the researched tag.
1398 * @return Corresponding element value when it exists, and the string
1399 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1401 std::string gdcmHeader::GetPubElValByNumber(guint16 group, guint16 element) {
1402 return PubElValSet.GetElValueByNumber(group, element);
1406 * \ingroup gdcmHeader
1407 * \brief Searches within the public dictionary for element value
1408 * representation of a given tag.
1410 * Obtaining the VR (Value Representation) might be needed by caller
1411 * to convert the string typed content to caller's native type
1412 * (think of C++ vs Python). The VR is actually of a higher level
1413 * of semantics than just the native C++ type.
1414 * @param group Group of the researched tag.
1415 * @param element Element of the researched tag.
1416 * @return Corresponding element value representation when it exists,
1417 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1419 std::string gdcmHeader::GetPubElValRepByNumber(guint16 group, guint16 element) {
1420 gdcmElValue* elem = PubElValSet.GetElementByNumber(group, element);
1422 return GDCM_UNFOUND;
1423 return elem->GetVR();
1427 * \ingroup gdcmHeader
1428 * \brief Searches within the public dictionary for element value of
1430 * @param TagName name of the researched element.
1431 * @return Corresponding element value when it exists, and the string
1432 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1434 std::string gdcmHeader::GetPubElValByName(std::string TagName) {
1435 return PubElValSet.GetElValueByName(TagName);
1439 * \ingroup gdcmHeader
1440 * \brief Searches within the elements parsed with the public dictionary for
1441 * the element value representation of a given tag.
1443 * Obtaining the VR (Value Representation) might be needed by caller
1444 * to convert the string typed content to caller's native type
1445 * (think of C++ vs Python). The VR is actually of a higher level
1446 * of semantics than just the native C++ type.
1447 * @param TagName name of the researched element.
1448 * @return Corresponding element value representation when it exists,
1449 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1451 std::string gdcmHeader::GetPubElValRepByName(std::string TagName) {
1452 gdcmElValue* elem = PubElValSet.GetElementByName(TagName);
1454 return GDCM_UNFOUND;
1455 return elem->GetVR();
1459 * \ingroup gdcmHeader
1460 * \brief Searches within elements parsed with the SHADOW dictionary
1461 * for the element value of a given tag.
1462 * @param group Group of the researched tag.
1463 * @param element Element of the researched tag.
1464 * @return Corresponding element value representation when it exists,
1465 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1467 std::string gdcmHeader::GetShaElValByNumber(guint16 group, guint16 element) {
1468 return ShaElValSet.GetElValueByNumber(group, element);
1472 * \ingroup gdcmHeader
1473 * \brief Searches within the elements parsed with the SHADOW dictionary
1474 * for the element value representation of a given tag.
1476 * Obtaining the VR (Value Representation) might be needed by caller
1477 * to convert the string typed content to caller's native type
1478 * (think of C++ vs Python). The VR is actually of a higher level
1479 * of semantics than just the native C++ type.
1480 * @param group Group of the researched tag.
1481 * @param element Element of the researched tag.
1482 * @return Corresponding element value representation when it exists,
1483 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1485 std::string gdcmHeader::GetShaElValRepByNumber(guint16 group, guint16 element) {
1486 gdcmElValue* elem = ShaElValSet.GetElementByNumber(group, element);
1488 return GDCM_UNFOUND;
1489 return elem->GetVR();
1493 * \ingroup gdcmHeader
1494 * \brief Searches within the elements parsed with the shadow dictionary
1495 * for an element value of given tag.
1496 * @param TagName name of the researched element.
1497 * @return Corresponding element value when it exists, and the string
1498 * GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1500 std::string gdcmHeader::GetShaElValByName(std::string TagName) {
1501 return ShaElValSet.GetElValueByName(TagName);
1505 * \ingroup gdcmHeader
1506 * \brief Searches within the elements parsed with the shadow dictionary for
1507 * the element value representation of a given tag.
1509 * Obtaining the VR (Value Representation) might be needed by caller
1510 * to convert the string typed content to caller's native type
1511 * (think of C++ vs Python). The VR is actually of a higher level
1512 * of semantics than just the native C++ type.
1513 * @param TagName name of the researched element.
1514 * @return Corresponding element value representation when it exists,
1515 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1517 std::string gdcmHeader::GetShaElValRepByName(std::string TagName) {
1518 gdcmElValue* elem = ShaElValSet.GetElementByName(TagName);
1520 return GDCM_UNFOUND;
1521 return elem->GetVR();
1525 * \ingroup gdcmHeader
1526 * \brief Searches within elements parsed with the public dictionary
1527 * and then within the elements parsed with the shadow dictionary
1528 * for the element value of a given tag.
1529 * @param group Group of the researched tag.
1530 * @param element Element of the researched tag.
1531 * @return Corresponding element value representation when it exists,
1532 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1534 std::string gdcmHeader::GetElValByNumber(guint16 group, guint16 element) {
1535 std::string pub = GetPubElValByNumber(group, element);
1538 return GetShaElValByNumber(group, element);
1542 * \ingroup gdcmHeader
1543 * \brief Searches within elements parsed with the public dictionary
1544 * and then within the elements parsed with the shadow dictionary
1545 * for the element value representation of a given tag.
1547 * Obtaining the VR (Value Representation) might be needed by caller
1548 * to convert the string typed content to caller's native type
1549 * (think of C++ vs Python). The VR is actually of a higher level
1550 * of semantics than just the native C++ type.
1551 * @param group Group of the researched tag.
1552 * @param element Element of the researched tag.
1553 * @return Corresponding element value representation when it exists,
1554 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1556 std::string gdcmHeader::GetElValRepByNumber(guint16 group, guint16 element) {
1557 std::string pub = GetPubElValRepByNumber(group, element);
1560 return GetShaElValRepByNumber(group, element);
1564 * \ingroup gdcmHeader
1565 * \brief Searches within elements parsed with the public dictionary
1566 * and then within the elements parsed with the shadow dictionary
1567 * for the element value of a given tag.
1568 * @param TagName name of the researched element.
1569 * @return Corresponding element value when it exists,
1570 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1572 std::string gdcmHeader::GetElValByName(std::string TagName) {
1573 std::string pub = GetPubElValByName(TagName);
1576 return GetShaElValByName(TagName);
1580 * \ingroup gdcmHeader
1581 * \brief Searches within elements parsed with the public dictionary
1582 * and then within the elements parsed with the shadow dictionary
1583 * for the element value representation of a given tag.
1585 * Obtaining the VR (Value Representation) might be needed by caller
1586 * to convert the string typed content to caller's native type
1587 * (think of C++ vs Python). The VR is actually of a higher level
1588 * of semantics than just the native C++ type.
1589 * @param TagName name of the researched element.
1590 * @return Corresponding element value representation when it exists,
1591 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
1593 std::string gdcmHeader::GetElValRepByName(std::string TagName) {
1594 std::string pub = GetPubElValRepByName(TagName);
1597 return GetShaElValRepByName(TagName);
1601 * \ingroup gdcmHeader
1602 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1603 * through it's (group, element) and modifies it's content with
1605 * @param content new value to substitute with
1606 * @param group group of the ElVal to modify
1607 * @param element element of the ElVal to modify
1609 int gdcmHeader::SetPubElValByNumber(std::string content, guint16 group,
1612 //TODO : homogeneiser les noms : SetPubElValByNumber
1613 // qui appelle PubElValSet.SetElValueByNumber
1614 // pourquoi pas SetPubElValueByNumber ??
1617 return ( PubElValSet.SetElValueByNumber (content, group, element) );
1621 * \ingroup gdcmHeader
1622 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1623 * through tag name and modifies it's content with the given value.
1624 * @param content new value to substitute with
1625 * @param TagName name of the tag to be modified
1627 int gdcmHeader::SetPubElValByName(std::string content, std::string TagName) {
1628 return ( PubElValSet.SetElValueByName (content, TagName) );
1632 * \ingroup gdcmHeader
1633 * \brief Accesses an existing gdcmElValue in the PubElValSet of this instance
1634 * through it's (group, element) and modifies it's length with
1636 * \warning Use with extreme caution.
1637 * @param length new length to substitute with
1638 * @param group group of the ElVal to modify
1639 * @param element element of the ElVal to modify
1640 * @return 1 on success, 0 otherwise.
1643 int gdcmHeader::SetPubElValLengthByNumber(guint32 length, guint16 group,
1645 return ( PubElValSet.SetElValueLengthByNumber (length, group, element) );
1649 * \ingroup gdcmHeader
1650 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1651 * through it's (group, element) and modifies it's content with
1653 * @param content new value to substitute with
1654 * @param group group of the ElVal to modify
1655 * @param element element of the ElVal to modify
1656 * @return 1 on success, 0 otherwise.
1658 int gdcmHeader::SetShaElValByNumber(std::string content,
1659 guint16 group, guint16 element) {
1660 return ( ShaElValSet.SetElValueByNumber (content, group, element) );
1664 * \ingroup gdcmHeader
1665 * \brief Accesses an existing gdcmElValue in the ShaElValSet of this instance
1666 * through tag name and modifies it's content with the given value.
1667 * @param content new value to substitute with
1668 * @param ShadowTagName name of the tag to be modified
1670 int gdcmHeader::SetShaElValByName(std::string content, std::string ShadowTagName) {
1671 return ( ShaElValSet.SetElValueByName (content, ShadowTagName) );
1675 * \ingroup gdcmHeader
1676 * \brief Parses the header of the file but WITHOUT loading element values.
1678 void gdcmHeader::ParseHeader(bool exception_on_error) throw(gdcmFormatError) {
1679 gdcmElValue * newElValue = (gdcmElValue *)0;
1683 while ( (newElValue = ReadNextElement()) ) {
1684 SkipElementValue(newElValue);
1685 PubElValSet.Add(newElValue);
1690 * \ingroup gdcmHeader
1691 * \brief This predicate, based on hopefully reasonnable heuristics,
1692 * decides whether or not the current gdcmHeader was properly parsed
1693 * and contains the mandatory information for being considered as
1694 * a well formed and usable image.
1695 * @return true when gdcmHeader is the one of a reasonable Dicom file,
1698 bool gdcmHeader::IsReadable(void) {
1699 if ( GetElValByName("Image Dimensions") != GDCM_UNFOUND
1700 && atoi(GetElValByName("Image Dimensions").c_str()) > 4 ) {
1703 if ( GetElValByName("Bits Allocated") == GDCM_UNFOUND )
1705 if ( GetElValByName("Bits Stored") == GDCM_UNFOUND )
1707 if ( GetElValByName("High Bit") == GDCM_UNFOUND )
1709 if ( GetElValByName("Pixel Representation") == GDCM_UNFOUND )
1715 * \ingroup gdcmHeader
1716 * \brief Small utility function that creates a new manually crafted
1717 * (as opposed as read from the file) gdcmElValue with user
1718 * specified name and adds it to the public tag hash table.
1719 * \note A fake TagKey is generated so the PubDict can keep it's coherence.
1720 * @param NewTagName The name to be given to this new tag.
1721 * @param VR The Value Representation to be given to this new tag.
1722 * @ return The newly hand crafted Element Value.
1724 gdcmElValue* gdcmHeader::NewManualElValToPubDict(std::string NewTagName,
1726 gdcmElValue* NewElVal = (gdcmElValue*)0;
1727 guint32 StuffGroup = 0xffff; // Group to be stuffed with additional info
1728 guint32 FreeElem = 0;
1729 gdcmDictEntry* NewEntry = (gdcmDictEntry*)0;
1731 FreeElem = PubElValSet.GenerateFreeTagKeyInGroup(StuffGroup);
1732 if (FreeElem == UINT32_MAX) {
1733 dbg.Verbose(1, "gdcmHeader::NewManualElValToPubDict",
1734 "Group 0xffff in Public Dict is full");
1735 return (gdcmElValue*)0;
1737 NewEntry = new gdcmDictEntry(StuffGroup, FreeElem,
1738 VR, "GDCM", NewTagName);
1739 NewElVal = new gdcmElValue(NewEntry);
1740 PubElValSet.Add(NewElVal);
1745 * \ingroup gdcmHeader
1746 * \brief Loads the element values of all the elements present in the
1747 * public tag based hash table.
1749 void gdcmHeader::LoadElements(void) {
1751 TagElValueHT ht = PubElValSet.GetTagHt();
1752 for (TagElValueHT::iterator tag = ht.begin(); tag != ht.end(); ++tag) {
1753 LoadElementValue(tag->second);
1757 // Load 'non string' values
1758 std::string PhotometricInterpretation = GetPubElValByNumber(0x0028,0x0004);
1759 if( PhotometricInterpretation == "PALETTE COLOR " ){
1760 LoadElementVoidArea(0x0028,0x1200); // gray LUT
1761 LoadElementVoidArea(0x0028,0x1201); // R LUT
1762 LoadElementVoidArea(0x0028,0x1202); // G LUT
1763 LoadElementVoidArea(0x0028,0x1203); // B LUT
1765 LoadElementVoidArea(0x0028,0x1221); // Segmented Red Palette Color LUT Data
1766 LoadElementVoidArea(0x0028,0x1222); // Segmented Green Palette Color LUT Data
1767 LoadElementVoidArea(0x0028,0x1223); // Segmented Blue Palette Color LUT Data
1770 // --------------------------------------------------------------
1771 // Special Patch to allow gdcm to read ACR-LibIDO formated images
1773 // if recognition code tells us we deal with a LibIDO image
1774 // we switch lineNumber and columnNumber
1776 std::string RecCode;
1777 RecCode = GetPubElValByNumber(0x0008, 0x0010);
1778 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
1779 RecCode == "CANRME_AILIBOD1_1." ) {
1780 filetype = ACR_LIBIDO;
1781 std::string rows = GetPubElValByNumber(0x0028, 0x0010);
1782 std::string columns = GetPubElValByNumber(0x0028, 0x0011);
1783 SetPubElValByNumber(columns, 0x0028, 0x0010);
1784 SetPubElValByNumber(rows , 0x0028, 0x0011);
1786 // ----------------- End of Special Patch ----------------
1790 * \ingroup gdcmHeader
1794 void gdcmHeader::PrintPubElVal(std::ostream & os) {
1795 PubElValSet.Print(os);
1799 * \ingroup gdcmHeader
1803 void gdcmHeader::PrintPubDict(std::ostream & os) {
1804 RefPubDict->Print(os);
1808 * \ingroup gdcmHeader
1810 * @return integer, acts as a Boolean
1812 int gdcmHeader::Write(FILE * fp, FileType type) {
1815 // TODO : move the following lines (and a lot of others)
1816 // to a future function CheckAndCorrectHeader
1818 if (type == ImplicitVR) {
1819 std::string implicitVRTransfertSyntax = "1.2.840.10008.1.2";
1820 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
1822 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1823 // values with a VR of UI shall be padded with a single trailing null
1824 // Dans le cas suivant on doit pader manuellement avec un 0
1826 PubElValSet.SetElValueLengthByNumber(18, 0x0002, 0x0010);
1829 if (type == ExplicitVR) {
1830 std::string explicitVRTransfertSyntax = "1.2.840.10008.1.2.1";
1831 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
1833 //FIXME Refer to standards on page 21, chapter 6.2 "Value representation":
1834 // values with a VR of UI shall be padded with a single trailing null
1835 // Dans le cas suivant on doit pader manuellement avec un 0
1837 PubElValSet.SetElValueLengthByNumber(20, 0x0002, 0x0010);
1840 return PubElValSet.Write(fp, type);
1844 // ------------------------ 'non string' elements related functions
1848 * \ingroup gdcmHeader
1849 * \brief Loads (from disk) the element content
1850 * when a string is not suitable
1852 void * gdcmHeader::LoadElementVoidArea(guint16 Group, guint16 Elem) {
1853 gdcmElValue * Element= PubElValSet.GetElementByNumber(Group, Elem);
1856 size_t o =(size_t)Element->GetOffset();
1857 fseek(fp, o, SEEK_SET);
1858 int l=Element->GetLength();
1859 void * a = malloc(l);
1861 std::cout << "Big Broblem (LoadElementVoidArea, malloc) "
1862 << std::hex << Group << " " << Elem << std::endl;
1865 /* int res = */ PubElValSet.SetVoidAreaByNumber(a, Group, Elem);
1866 // TODO check the result
1867 size_t l2 = fread(a, 1, l ,fp);
1869 std::cout << "Big Broblem (LoadElementVoidArea, fread) "
1870 << std::hex << Group << " " << Elem << std::endl;
1878 * \ingroup gdcmHeader
1879 * \brief Gets (from Header) the offset of a 'non string' element value
1880 * \ (LoadElementValue has already be executed)
1883 * @return File Offset of the Element Value
1885 size_t gdcmHeader::GetPubElValOffsetByNumber(guint16 Group, guint16 Elem) {
1886 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1888 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1889 "failed to Locate gdcmElValue");
1892 return elValue->GetOffset();
1896 * \ingroup gdcmHeader
1897 * \brief Gets (from Header) a 'non string' element value
1898 * \ (LoadElementValue has already be executed)
1901 * @return Pointer to the 'non string' area
1904 void * gdcmHeader::GetPubElValVoidAreaByNumber(guint16 Group, guint16 Elem) {
1905 gdcmElValue* elValue = PubElValSet.GetElementByNumber(Group, Elem);
1907 dbg.Verbose(1, "gdcmHeader::GetElValueByNumber",
1908 "failed to Locate gdcmElValue");
1911 return elValue->GetVoidArea();
1916 // =============================================================================
1917 // Heuristics based accessors
1918 //==============================================================================
1921 // TODO : move to an other file.
1925 * \ingroup gdcmHeader
1926 * \brief Retrieve the number of columns of image.
1927 * @return The encountered size when found, 0 by default.
1929 int gdcmHeader::GetXSize(void) {
1930 // We cannot check for "Columns" because the "Columns" tag is present
1931 // both in IMG (0028,0011) and OLY (6000,0011) sections of the dictionary.
1932 std::string StrSize = GetPubElValByNumber(0x0028,0x0011);
1933 if (StrSize == GDCM_UNFOUND)
1935 return atoi(StrSize.c_str());
1939 * \ingroup gdcmHeader
1940 * \brief Retrieve the number of lines of image.
1941 * \warning The defaulted value is 1 as opposed to gdcmHeader::GetXSize()
1942 * @return The encountered size when found, 1 by default.
1944 int gdcmHeader::GetYSize(void) {
1945 // We cannot check for "Rows" because the "Rows" tag is present
1946 // both in IMG (0028,0010) and OLY (6000,0010) sections of the dictionary.
1947 std::string StrSize = GetPubElValByNumber(0x0028,0x0010);
1948 if (StrSize != GDCM_UNFOUND)
1949 return atoi(StrSize.c_str());
1953 // The Rows (0028,0010) entry is optional for ACR/NEMA. It might
1954 // hence be a signal (1d image). So we default to 1:
1959 * \ingroup gdcmHeader
1960 * \brief Retrieve the number of planes of volume or the number
1961 * of frames of a multiframe.
1962 * \warning When present we consider the "Number of Frames" as the third
1963 * dimension. When absent we consider the third dimension as
1964 * being the "Planes" tag content.
1965 * @return The encountered size when found, 1 by default.
1967 int gdcmHeader::GetZSize(void) {
1968 // Both in DicomV3 and ACR/Nema the consider the "Number of Frames"
1969 // as the third dimension.
1970 std::string StrSize = GetPubElValByNumber(0x0028,0x0008);
1971 if (StrSize != GDCM_UNFOUND)
1972 return atoi(StrSize.c_str());
1974 // We then consider the "Planes" entry as the third dimension [we
1975 // cannot retrieve by name since "Planes tag is present both in
1976 // IMG (0028,0012) and OLY (6000,0012) sections of the dictionary].
1977 StrSize = GetPubElValByNumber(0x0028,0x0012);
1978 if (StrSize != GDCM_UNFOUND)
1979 return atoi(StrSize.c_str());
1984 * \ingroup gdcmHeader
1985 * \brief Retrieve the number of Bits Stored
1986 * (as opposite to number of Bits Allocated)
1988 * @return The encountered number of Bits Stored, 0 by default.
1990 int gdcmHeader::GetBitsStored(void) {
1991 std::string StrSize = GetPubElValByNumber(0x0028,0x0101);
1992 if (StrSize == GDCM_UNFOUND)
1994 return atoi(StrSize.c_str());
1998 * \ingroup gdcmHeader
1999 * \brief Retrieve the number of Bits Allocated
2000 * (8, 12 -compacted ACR-NEMA files, 16, ...)
2002 * @return The encountered number of Bits Allocated, 0 by default.
2004 int gdcmHeader::GetBitsAllocated(void) {
2005 std::string StrSize = GetPubElValByNumber(0x0028,0x0100);
2006 if (StrSize == GDCM_UNFOUND)
2008 return atoi(StrSize.c_str());
2012 * \ingroup gdcmHeader
2013 * \brief Retrieve the number of Samples Per Pixel
2014 * (1 : gray level, 3 : RGB -1 or 3 Planes-)
2016 * @return The encountered number of Samples Per Pixel, 1 by default.
2018 int gdcmHeader::GetSamplesPerPixel(void) {
2019 std::string StrSize = GetPubElValByNumber(0x0028,0x0002);
2020 if (StrSize == GDCM_UNFOUND)
2021 return 1; // Well, it's supposed to be mandatory ...
2022 return atoi(StrSize.c_str());
2026 * \ingroup gdcmHeader
2027 * \brief Retrieve the Planar Configuration for RGB images
2028 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
2030 * @return The encountered Planar Configuration, 0 by default.
2032 int gdcmHeader::GetPlanarConfiguration(void) {
2033 std::string StrSize = GetPubElValByNumber(0x0028,0x0006);
2034 if (StrSize == GDCM_UNFOUND)
2036 return atoi(StrSize.c_str());
2040 * \ingroup gdcmHeader
2041 * \brief Return the size (in bytes) of a single pixel of data.
2042 * @return The size in bytes of a single pixel of data.
2045 int gdcmHeader::GetPixelSize(void) {
2046 std::string PixelType = GetPixelType();
2047 if (PixelType == "8U" || PixelType == "8S")
2049 if (PixelType == "16U" || PixelType == "16S")
2051 if (PixelType == "32U" || PixelType == "32S")
2053 dbg.Verbose(0, "gdcmHeader::GetPixelSize: Unknown pixel type");
2058 * \ingroup gdcmHeader
2059 * \brief Build the Pixel Type of the image.
2060 * Possible values are:
2061 * - 8U unsigned 8 bit,
2062 * - 8S signed 8 bit,
2063 * - 16U unsigned 16 bit,
2064 * - 16S signed 16 bit,
2065 * - 32U unsigned 32 bit,
2066 * - 32S signed 32 bit,
2067 * \warning 12 bit images appear as 16 bit.
2068 * \ 24 bit images appear as 8 bit
2071 std::string gdcmHeader::GetPixelType(void) {
2072 std::string BitsAlloc;
2073 BitsAlloc = GetElValByName("Bits Allocated");
2074 if (BitsAlloc == GDCM_UNFOUND) {
2075 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Bits Allocated");
2076 BitsAlloc = std::string("16");
2078 if (BitsAlloc == "12") // It will be unpacked
2079 BitsAlloc = std::string("16");
2080 else if (BitsAlloc == "24") // (in order no to be messed up
2081 BitsAlloc = std::string("8"); // by old RGB images)
2084 Signed = GetElValByName("Pixel Representation");
2085 if (Signed == GDCM_UNFOUND) {
2086 dbg.Verbose(0, "gdcmHeader::GetPixelType: unfound Pixel Representation");
2087 BitsAlloc = std::string("0");
2090 Signed = std::string("U");
2093 std::cout << "GetPixelType : " << BitsAlloc + Signed << std::endl;
2094 Signed = std::string("S");
2096 return( BitsAlloc + Signed);
2100 * \ingroup gdcmHeader
2101 * \brief gets the info from 0002,0010 : Transfert Syntax
2103 * @return Transfert Syntax Name (as oposite to Transfert Syntax UID)
2105 std::string gdcmHeader::GetTransferSyntaxName(void) {
2106 std::string TransfertSyntax = GetPubElValByNumber(0x0002,0x0010);
2107 if (TransfertSyntax == GDCM_UNFOUND) {
2108 dbg.Verbose(0, "gdcmHeader::GetTransferSyntaxName: unfound Transfert Syntax (0002,0010)");
2109 return "Uncompressed ACR-NEMA";
2111 // we do it only when we need it
2112 gdcmTS * ts = gdcmGlobal::GetTS();
2113 std::string tsName=ts->GetValue(TransfertSyntax);
2114 //delete ts; // Seg Fault when deleted ?!
2118 // -------------------------------- Lookup Table related functions ------------
2121 * \ingroup gdcmHeader
2122 * \brief tells us if LUT are used
2123 * \warning Right now, Segmented xxx Palette Color Lookup Table Data
2124 * \ are NOT considered as LUT, since nobody knows
2125 *\ how to deal with them
2126 * @return int acts as a Boolean
2129 int gdcmHeader::HasLUT(void) {
2131 // Check the presence of the LUT Descriptors
2132 if (GetPubElValByNumber(0x0028,0x1101) == GDCM_UNFOUND)
2134 // LutDescriptorGreen
2135 if (GetPubElValByNumber(0x0028,0x1102) == GDCM_UNFOUND)
2137 // LutDescriptorBlue
2138 if (GetPubElValByNumber(0x0028,0x1103) == GDCM_UNFOUND)
2142 if (GetPubElValByNumber(0x0028,0x1201) == GDCM_UNFOUND)
2144 if (GetPubElValByNumber(0x0028,0x1202) == GDCM_UNFOUND)
2146 if (GetPubElValByNumber(0x0028,0x1203) == GDCM_UNFOUND)
2152 * \ingroup gdcmHeader
2153 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
2155 * @return Lookup Table nBit
2156 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2159 int gdcmHeader::GetLUTNbits(void) {
2160 std::vector<std::string> tokens;
2164 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red = Lookup Table Desc-Blue
2165 // Consistency already checked in GetLUTLength
2166 std::string LutDescription = GetPubElValByNumber(0x0028,0x1101);
2167 if (LutDescription == GDCM_UNFOUND)
2169 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2170 Tokenize (LutDescription, tokens, "\\");
2171 //LutLength=atoi(tokens[0].c_str());
2172 //LutDepth=atoi(tokens[1].c_str());
2173 LutNbits=atoi(tokens[2].c_str());
2179 * \ingroup gdcmHeader
2180 * \brief builts Red/Green/Blue/Alpha LUT from Header
2181 * \ when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
2182 * \ and (0028,1101),(0028,1102),(0028,1102)
2183 * \ - xxx Palette Color Lookup Table Descriptor - are found
2184 * \ and (0028,1201),(0028,1202),(0028,1202)
2185 * \ - xxx Palette Color Lookup Table Data - are found
2186 * \warning does NOT deal with :
2187 * \ 0028 1100 Gray Lookup Table Descriptor (Retired)
2188 * \ 0028 1221 Segmented Red Palette Color Lookup Table Data
2189 * \ 0028 1222 Segmented Green Palette Color Lookup Table Data
2190 * \ 0028 1223 Segmented Blue Palette Color Lookup Table Data
2191 * \ no known Dicom reader deails with them :-(
2192 * @return Lookup Table RGBA
2195 void * gdcmHeader::GetLUTRGBA(void) {
2196 // Not so easy : see
2197 // http://www.barre.nom.fr/medical/dicom2/limitations.html#Color%20Lookup%20Tables
2198 // and OT-PAL-8-face.dcm
2200 // if Photometric Interpretation # PALETTE COLOR, no LUT to be done
2202 if (gdcmHeader::GetPubElValByNumber(0x0028,0x0004) != "PALETTE COLOR ") {
2206 void * LutR,*LutG,*LutB;
2208 int lengthR, debR, nbitsR;
2209 int lengthG, debG, nbitsG;
2210 int lengthB, debB, nbitsB;
2212 // Get info from Lut Descriptors
2213 // (the 3 LUT descriptors may be different)
2215 std::string LutDescriptionR = GetPubElValByNumber(0x0028,0x1101);
2216 if (LutDescriptionR == GDCM_UNFOUND)
2218 std::string LutDescriptionG = GetPubElValByNumber(0x0028,0x1102);
2219 if (LutDescriptionG == GDCM_UNFOUND)
2221 std::string LutDescriptionB = GetPubElValByNumber(0x0028,0x1103);
2222 if (LutDescriptionB == GDCM_UNFOUND)
2225 std::vector<std::string> tokens;
2227 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2228 Tokenize (LutDescriptionR, tokens, "\\");
2229 lengthR=atoi(tokens[0].c_str()); // Red LUT length in Bytes
2230 debR =atoi(tokens[1].c_str()); // subscript of the first Lut Value
2231 nbitsR =atoi(tokens[2].c_str()); // Lut item size (in Bits)
2234 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2235 Tokenize (LutDescriptionG, tokens, "\\");
2236 lengthG=atoi(tokens[0].c_str()); // Green LUT length in Bytes
2237 debG =atoi(tokens[1].c_str());
2238 nbitsG =atoi(tokens[2].c_str());
2241 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
2242 Tokenize (LutDescriptionB, tokens, "\\");
2243 lengthB=atoi(tokens[0].c_str()); // Blue LUT length in Bytes
2244 debB =atoi(tokens[1].c_str());
2245 nbitsB =atoi(tokens[2].c_str());
2248 // Load LUTs into memory, (as they were stored on disk)
2250 unsigned char *lutR =(unsigned char *)
2251 GetPubElValVoidAreaByNumber(0x0028,0x1201);
2252 unsigned char *lutG =(unsigned char *)
2253 GetPubElValVoidAreaByNumber(0x0028,0x1202);
2254 unsigned char *lutB =(unsigned char *)
2255 GetPubElValVoidAreaByNumber(0x0028,0x1203);
2257 if (!lutR || !lutG || !lutB ) {
2260 // forge the 4 * 8 Bits Red/Green/Blue/Alpha LUT
2262 char *LUTRGBA = (char *)calloc(1024,1); // 256 * 4 (R, G, B, Alpha)
2266 memset(LUTRGBA, 0, 1024);
2269 std::string str_nb = GetPubElValByNumber(0x0028,0x0100);
2270 if (str_nb == GDCM_UNFOUND ) {
2273 nb = atoi(str_nb.c_str() );
2277 if (nbitsR==16 && nb==8) // when LUT item size is different than pixel size
2278 mult=2; // high byte must be = low byte
2279 else // See PS 3.3-2003 C.11.1.1.2 p 619
2283 // if we get a black image, let's just remove the '+1'
2284 // from 'i*mult+1' and check again
2285 // if it works, we shall have to check the 3 Palettes
2286 // to see which byte is ==0 (first one, or second one)
2288 // We give up the checking to avoid some overhead
2293 for(i=0;i<lengthR;i++) {
2294 *a = lutR[i*mult+1];
2298 for(i=0;i<lengthG;i++) {
2299 *a = lutG[i*mult+1];
2303 for(i=0;i<lengthB;i++) {
2304 *a = lutB[i*mult+1];
2308 for(i=0;i<255;i++) {
2309 *a = 1; // Alpha component
2313 //How to free the now useless LUTs?
2315 //free(LutR); free(LutB); free(LutG);