1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/22 15:31:17 $
7 Version: $Revision: 1.25 $
9 Copyright (c) CREATIS (Centre de Recherche et d'Applications en Traitement de
10 l'Image). All rights reserved. See Doc/License.txt or
11 http://www.creatis.insa-lyon.fr/Public/Gdcm/License.htm for details.
13 This software is distributed WITHOUT ANY WARRANTY; without even
14 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 PURPOSE. See the above copyright notices for more information.
17 =========================================================================*/
19 #include "gdcmDocument.h"
20 #include "gdcmValEntry.h"
21 #include "gdcmBinEntry.h"
22 #include "gdcmSeqEntry.h"
24 #include "gdcmGlobal.h"
26 #include "gdcmDebug.h"
35 #include <netinet/in.h>
40 // Implicit VR Little Endian
41 #define UI1_2_840_10008_1_2 "1.2.840.10008.1.2"
42 // Explicit VR Little Endian
43 #define UI1_2_840_10008_1_2_1 "1.2.840.10008.1.2.1"
44 // Deflated Explicit VR Little Endian
45 #define UI1_2_840_10008_1_2_1_99 "1.2.840.10008.1.2.1.99"
46 // Explicit VR Big Endian
47 #define UI1_2_840_10008_1_2_2 "1.2.840.10008.1.2.2"
48 // JPEG Baseline (Process 1)
49 #define UI1_2_840_10008_1_2_4_50 "1.2.840.10008.1.2.4.50"
50 // JPEG Extended (Process 2 & 4)
51 #define UI1_2_840_10008_1_2_4_51 "1.2.840.10008.1.2.4.51"
52 // JPEG Extended (Process 3 & 5)
53 #define UI1_2_840_10008_1_2_4_52 "1.2.840.10008.1.2.4.52"
54 // JPEG Spectral Selection, Non-Hierarchical (Process 6 & 8)
55 #define UI1_2_840_10008_1_2_4_53 "1.2.840.10008.1.2.4.53"
56 // JPEG Full Progression, Non-Hierarchical (Process 10 & 12)
57 #define UI1_2_840_10008_1_2_4_55 "1.2.840.10008.1.2.4.55"
58 // JPEG Lossless, Non-Hierarchical (Process 14)
59 #define UI1_2_840_10008_1_2_4_57 "1.2.840.10008.1.2.4.57"
60 // JPEG Lossless, Hierarchical, First-Order Prediction (Process 14,
61 // [Selection Value 1])
62 #define UI1_2_840_10008_1_2_4_70 "1.2.840.10008.1.2.4.70"
64 #define UI1_2_840_10008_1_2_4_90 "1.2.840.10008.1.2.4.90"
66 #define UI1_2_840_10008_1_2_4_91 "1.2.840.10008.1.2.4.91"
68 #define UI1_2_840_10008_1_2_5 "1.2.840.10008.1.2.5"
69 // UI1_1_2_840_10008_1_2_5
70 #define str2num(str, typeNum) *((typeNum *)(str))
72 //-----------------------------------------------------------------------------
73 // Refer to gdcmDocument::CheckSwap()
74 const unsigned int gdcmDocument::HEADER_LENGTH_TO_READ = 256;
76 // Refer to gdcmDocument::SetMaxSizeLoadEntry()
77 const unsigned int gdcmDocument::MAX_SIZE_LOAD_ELEMENT_VALUE = 4096;
79 const unsigned int gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE = 64;
81 //-----------------------------------------------------------------------------
82 // Constructor / Destructor
86 * @param inFilename file to be opened for parsing
87 * @param exception_on_error whether we throw an exception or not
88 * @param enable_sequences = true to allow the header
89 * to be parsed *inside* the SeQuences,
90 * when they have an actual length
91 * \warning enable_sequences *has to be* true for reading PAPYRUS 3.0 files
92 * @param ignore_shadow to allow skipping the shadow elements,
93 * to save memory space.
94 * \warning The TRUE value for this param has to be used
95 * with a FALSE value for the 'enable_sequence' param.
96 * ('public elements' may be embedded in 'shadow Sequences')
98 gdcmDocument::gdcmDocument(std::string const & inFilename,
99 bool exception_on_error,
100 bool enable_sequences,
102 : gdcmElementSet(-1) {
103 enableSequences=enable_sequences;
104 IgnoreShadow =ignore_shadow;
106 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
107 Filename = inFilename;
110 if ( !OpenFile(exception_on_error))
113 dbg.Verbose(0, "gdcmDocument::gdcmDocument: starting parsing of file: ",
117 fseek(fp,0L,SEEK_END);
118 long lgt = ftell(fp);
122 long beg = ftell(fp);
127 long l=ParseDES( this, beg, lgt, false); // le Load sera fait a la volee
128 (void)l; //is l used anywhere ?
131 // --------------------------------------------------------------
132 // Special Patch to allow gdcm to read ACR-LibIDO formated images
134 // if recognition code tells us we deal with a LibIDO image
135 // we switch lineNumber and columnNumber
138 RecCode = GetEntryByNumber(0x0008, 0x0010); // recognition code
139 if (RecCode == "ACRNEMA_LIBIDO_1.1" ||
140 RecCode == "CANRME_AILIBOD1_1." ) // for brain-damaged softwares
141 // with "little-endian strings"
143 Filetype = gdcmACR_LIBIDO;
144 std::string rows = GetEntryByNumber(0x0028, 0x0010);
145 std::string columns = GetEntryByNumber(0x0028, 0x0011);
146 SetEntryByNumber(columns, 0x0028, 0x0010);
147 SetEntryByNumber(rows , 0x0028, 0x0011);
149 // ----------------- End of Special Patch ----------------
151 printLevel = 1; // 'Medium' print level by default
156 * @param exception_on_error
158 gdcmDocument::gdcmDocument(bool exception_on_error)
159 :gdcmElementSet(-1) {
160 (void)exception_on_error;
163 SetMaxSizeLoadEntry(MAX_SIZE_LOAD_ELEMENT_VALUE);
166 printLevel = 1; // 'Medium' print level by default
170 * \brief Canonical destructor.
172 gdcmDocument::~gdcmDocument (void) {
176 // Recursive clean up of sequences
177 for (TagDocEntryHT::iterator it = tagHT.begin(); it != tagHT.end(); ++it )
184 //-----------------------------------------------------------------------------
188 * \brief Prints The Dict Entries of THE public Dicom Dictionary
191 void gdcmDocument::PrintPubDict(std::ostream & os) {
192 RefPubDict->Print(os);
196 * \brief Prints The Dict Entries of THE shadow Dicom Dictionary
199 void gdcmDocument::PrintShaDict(std::ostream & os) {
200 RefShaDict->Print(os);
203 //-----------------------------------------------------------------------------
206 * \brief Get the public dictionary used
208 gdcmDict *gdcmDocument::GetPubDict(void) {
213 * \brief Get the shadow dictionary used
215 gdcmDict *gdcmDocument::GetShaDict(void) {
220 * \brief Set the shadow dictionary used
221 * \param dict dictionary to use in shadow
223 bool gdcmDocument::SetShaDict(gdcmDict *dict){
229 * \brief Set the shadow dictionary used
230 * \param dictName name of the dictionary to use in shadow
232 bool gdcmDocument::SetShaDict(DictKey dictName){
233 RefShaDict=gdcmGlobal::GetDicts()->GetDict(dictName);
238 * \brief This predicate, based on hopefully reasonable heuristics,
239 * decides whether or not the current gdcmDocument was properly parsed
240 * and contains the mandatory information for being considered as
241 * a well formed and usable Dicom/Acr File.
242 * @return true when gdcmDocument is the one of a reasonable Dicom/Acr file,
245 bool gdcmDocument::IsReadable(void) {
246 if(Filetype==gdcmUnknown) {
247 dbg.Verbose(0, "gdcmDocument::IsReadable: wrong filetype");
250 if(!tagHT.empty()<=0) {
251 dbg.Verbose(0, "gdcmDocument::IsReadable: no tags in internal"
261 * \brief Internal function that checks whether the Transfer Syntax given
262 * as argument is the one present in the current document.
263 * @param SyntaxToCheck The transfert syntax we need to check against.
264 * @return True when SyntaxToCheck corresponds to the Transfer Syntax of
265 * the current document. False either when the document contains
266 * no Transfer Syntax, or when the Tranfer Syntaxes don't match.
268 bool gdcmDocument::IsGivenTransferSyntax(const std::string & SyntaxToCheck)
270 gdcmDocEntry *Entry = GetDocEntryByNumber(0x0002, 0x0010);
274 // The entry might be present but not loaded (parsing and loading
275 // happen at differente stages): try loading and proceed with check...
276 LoadDocEntrySafe(Entry);
277 if (gdcmValEntry* ValEntry = dynamic_cast< gdcmValEntry* >(Entry) )
279 std::string Transfer = ValEntry->GetValue();
280 // The actual transfer (as read from disk) might be padded. We
281 // first need to remove the potential padding. We can make the
282 // weak assumption that padding was not executed with digits...
283 while ( ! isdigit(Transfer[Transfer.length()-1]) )
285 Transfer.erase(Transfer.length()-1, 1);
287 if ( Transfer == SyntaxToCheck )
294 * \brief Determines if the Transfer Syntax of the present document
295 * corresponds to a Implicit Value Representation of
297 * \sa \ref gdcmDocument::IsGivenTransferSyntax.
298 * @return True when ImplicitVRLittleEndian found. False in all other cases.
300 bool gdcmDocument::IsImplicitVRLittleEndianTransferSyntax(void)
302 return IsGivenTransferSyntax(UI1_2_840_10008_1_2);
306 * \brief Determines if the Transfer Syntax was already encountered
307 * and if it corresponds to a ExplicitVRLittleEndian one.
308 * @return True when ExplicitVRLittleEndian found. False in all other cases.
310 bool gdcmDocument::IsExplicitVRLittleEndianTransferSyntax(void)
312 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1);
316 * \brief Determines if the Transfer Syntax was already encountered
317 * and if it corresponds to a DeflatedExplicitVRLittleEndian one.
318 * @return True when DeflatedExplicitVRLittleEndian found. False in all other cases.
320 bool gdcmDocument::IsDeflatedExplicitVRLittleEndianTransferSyntax(void)
322 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_1_99);
326 * \brief Determines if the Transfer Syntax was already encountered
327 * and if it corresponds to a Explicit VR Big Endian one.
328 * @return True when big endian found. False in all other cases.
330 bool gdcmDocument::IsExplicitVRBigEndianTransferSyntax(void)
332 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_2);
336 * \brief Determines if the Transfer Syntax was already encountered
337 * and if it corresponds to a JPEGBaseLineProcess1 one.
338 * @return True when JPEGBaseLineProcess1found. False in all other cases.
340 bool gdcmDocument::IsJPEGBaseLineProcess1TransferSyntax(void)
342 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_50);
346 * \brief Determines if the Transfer Syntax was already encountered
347 * and if it corresponds to a JPEGExtendedProcess2-4 one.
348 * @return True when JPEGExtendedProcess2-4 found. False in all other cases.
350 bool gdcmDocument::IsJPEGExtendedProcess2_4TransferSyntax(void)
352 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_51);
356 * \brief Determines if the Transfer Syntax was already encountered
357 * and if it corresponds to a JPEGExtendeProcess3-5 one.
358 * @return True when JPEGExtendedProcess3-5 found. False in all other cases.
360 bool gdcmDocument::IsJPEGExtendedProcess3_5TransferSyntax(void)
362 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_52);
366 * \brief Determines if the Transfer Syntax was already encountered
367 * and if it corresponds to a JPEGSpectralSelectionProcess6-8 one.
368 * @return True when JPEGSpectralSelectionProcess6-8 found. False in all
371 bool gdcmDocument::IsJPEGSpectralSelectionProcess6_8TransferSyntax(void)
373 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_53);
377 * \brief Determines if the Transfer Syntax was already encountered
378 * and if it corresponds to a RLE Lossless one.
379 * @return True when RLE Lossless found. False in all
382 bool gdcmDocument::IsRLELossLessTransferSyntax(void)
384 return IsGivenTransferSyntax(UI1_2_840_10008_1_2_5);
388 * \brief Determines if Transfer Syntax was already encountered
389 * and if it corresponds to a JPEG Lossless one.
390 * @return True when RLE Lossless found. False in all
393 bool gdcmDocument::IsJPEGLossless(void)
395 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_55)
396 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_57)
397 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90) );
401 * \brief Determines if the Transfer Syntax was already encountered
402 * and if it corresponds to a JPEG2000 one
403 * @return True when JPEG2000 (Lossly or LossLess) found. False in all
406 bool gdcmDocument::IsJPEG2000(void)
408 return ( IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_90)
409 || IsGivenTransferSyntax(UI1_2_840_10008_1_2_4_91) );
413 * \brief Predicate for dicom version 3 file.
414 * @return True when the file is a dicom version 3.
416 bool gdcmDocument::IsDicomV3(void) {
417 // Checking if Transfert Syntax exists is enough
418 // Anyway, it's to late check if the 'Preamble' was found ...
419 // And ... would it be a rich idea to check ?
420 // (some 'no Preamble' DICOM images exist !)
421 return (GetDocEntryByNumber(0x0002, 0x0010) != NULL);
425 * \brief returns the File Type
426 * (ACR, ACR_LIBIDO, ExplicitVR, ImplicitVR, Unknown)
427 * @return the FileType code
429 FileType gdcmDocument::GetFileType(void) {
434 * \brief opens the file
435 * @param exception_on_error
438 FILE *gdcmDocument::OpenFile(bool exception_on_error)
441 fp=fopen(Filename.c_str(),"rb");
445 if(exception_on_error)
446 throw gdcmFileError("gdcmDocument::gdcmDocument(const char *, bool)");
449 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file: ",
458 fread(&zero, (size_t)2, (size_t)1, fp);
460 //ACR -- or DICOM with no Preamble --
461 if( zero == 0x0008 || zero == 0x0800 || zero == 0x0002 || zero == 0x0200)
465 fseek(fp, 126L, SEEK_CUR);
467 fread(dicm, (size_t)4, (size_t)1, fp);
468 if( memcmp(dicm, "DICM", 4) == 0 )
472 dbg.Verbose(0, "gdcmDocument::OpenFile not DICOM/ACR", Filename.c_str());
475 dbg.Verbose(0, "gdcmDocument::OpenFile cannot open file", Filename.c_str());
481 * \brief closes the file
482 * @return TRUE if the close was successfull
484 bool gdcmDocument::CloseFile(void) {
485 int closed = fclose(fp);
493 * \brief Writes in a file all the Header Entries (Dicom Elements)
494 * @param fp file pointer on an already open file
495 * @param filetype Type of the File to be written
496 * (ACR-NEMA, ExplicitVR, ImplicitVR)
497 * \return Always true.
499 bool gdcmDocument::WriteF(FileType filetype) {
502 /// The stuff is rewritten using the SeQuence based
503 /// tree-like stucture (cf : Print )
507 /// \todo move the following lines (and a lot of others, to be written)
508 /// to a future function CheckAndCorrectHeader
510 /// WARNING : Si on veut ecrire du DICOM V3 a partir d'un DcmHeader ACR-NEMA
511 /// no way (check : FileType est un champ de gdcmDocument ...)
512 /// a moins de se livrer a un tres complique ajout des champs manquants.
513 /// faire un CheckAndCorrectHeader (?)
515 if (filetype == gdcmImplicitVR)
517 std::string implicitVRTransfertSyntax = UI1_2_840_10008_1_2;
518 ReplaceOrCreateByNumber(implicitVRTransfertSyntax,0x0002, 0x0010);
520 /// \todo Refer to standards on page 21, chapter 6.2
521 /// "Value representation": values with a VR of UI shall be
522 /// padded with a single trailing null
523 /// Dans le cas suivant on doit pader manuellement avec un 0
525 SetEntryLengthByNumber(18, 0x0002, 0x0010);
528 if (filetype == gdcmExplicitVR)
530 std::string explicitVRTransfertSyntax = UI1_2_840_10008_1_2_1;
531 ReplaceOrCreateByNumber(explicitVRTransfertSyntax,0x0002, 0x0010);
533 /// \todo Refer to standards on page 21, chapter 6.2
534 /// "Value representation": values with a VR of UI shall be
535 /// padded with a single trailing null
536 /// Dans le cas suivant on doit pader manuellement avec un 0
538 SetEntryLengthByNumber(20, 0x0002, 0x0010);
542 * \todo rewrite later, if really usefull
543 * ('Group Length' element is optional in DICOM)
545 * --> Warning : un-updated odd groups lengthes can causes pb
546 * --> (xmedcon breaks)
547 * --> to be re- written with future org.
549 * if ( (filetype == ImplicitVR) || (filetype == ExplicitVR) )
550 * UpdateGroupLength(false,filetype);
551 * if ( filetype == ACR)
552 * UpdateGroupLength(true,ACR);
555 Write(fp,filetype); // the gdcmElementSet one !
557 /// WriteEntries(fp,type); // old stuff
562 * \brief Modifies the value of a given Header Entry (Dicom Element)
563 * when it exists. Create it with the given value when unexistant.
564 * @param Value (string) Value to be set
565 * @param Group Group number of the Entry
566 * @param Elem Element number of the Entry
567 * \return pointer to the modified/created Header Entry (NULL when creation
571 gdcmValEntry * gdcmDocument::ReplaceOrCreateByNumber(
576 gdcmDocEntry* CurrentEntry;
577 gdcmValEntry* ValEntry;
579 CurrentEntry = GetDocEntryByNumber( Group, Elem);
582 // The entry wasn't present and we simply create the required ValEntry:
583 CurrentEntry = NewDocEntryByNumber(Group, Elem);
586 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: call to"
587 " NewDocEntryByNumber failed.");
590 ValEntry = new gdcmValEntry(CurrentEntry);
591 if ( !AddEntry(ValEntry))
593 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: AddEntry"
594 " failed allthough this is a creation.");
599 ValEntry = dynamic_cast< gdcmValEntry* >(CurrentEntry);
602 // We need to promote the gdcmDocEntry to a gdcmValEntry:
603 ValEntry = new gdcmValEntry(CurrentEntry);
604 if (!RemoveEntry(CurrentEntry))
606 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: removal"
607 " of previous DocEntry failed.");
610 if ( !AddEntry(ValEntry))
612 dbg.Verbose(0, "gdcmDocument::ReplaceOrCreateByNumber: adding"
613 " promoted ValEntry failed.");
619 SetEntryByNumber(Value, Group, Elem);
625 * \brief Modifies the value of a given Header Entry (Dicom Element)
626 * when it exists. Create it with the given value when unexistant.
627 * @param voidArea (binary) value to be set
628 * @param Group Group number of the Entry
629 * @param Elem Element number of the Entry
630 * \return pointer to the modified/created Header Entry (NULL when creation
633 gdcmBinEntry * gdcmDocument::ReplaceOrCreateByNumber(
641 a = GetDocEntryByNumber( Group, Elem);
643 a =NewBinEntryByNumber(Group, Elem);
647 b = new gdcmBinEntry(a);
650 SetEntryByNumber(voidArea, lgth, Group, Elem);
651 b->SetVoidArea(voidArea);
659 * \brief Set a new value if the invoked element exists
660 * Seems to be useless !!!
661 * @param Value new element value
662 * @param Group group number of the Entry
663 * @param Elem element number of the Entry
666 bool gdcmDocument::ReplaceIfExistByNumber(char* Value, guint16 Group, guint16 Elem )
668 std::string v = Value;
669 SetEntryByNumber(v, Group, Elem);
673 //-----------------------------------------------------------------------------
677 * \brief Checks if a given Dicom Element exists within the H table
678 * @param group Group number of the searched Dicom Element
679 * @param element Element number of the searched Dicom Element
680 * @return number of occurences
682 int gdcmDocument::CheckIfEntryExistByNumber(guint16 group, guint16 element ) {
683 std::string key = gdcmDictEntry::TranslateToKey(group, element );
684 return tagHT.count(key);
688 * \brief Searches within Header Entries (Dicom Elements) parsed with
689 * the public and private dictionaries
690 * for the element value of a given tag.
691 * \warning Don't use any longer : use GetPubEntryByName
692 * @param tagName name of the searched element.
693 * @return Corresponding element value when it exists,
694 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
696 std::string gdcmDocument::GetEntryByName(std::string tagName) {
697 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
698 if( dictEntry == NULL)
701 return GetEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement());
705 * \brief Searches within Header Entries (Dicom Elements) parsed with
706 * the public and private dictionaries
707 * for the element value representation of a given tag.
709 * Obtaining the VR (Value Representation) might be needed by caller
710 * to convert the string typed content to caller's native type
711 * (think of C++ vs Python). The VR is actually of a higher level
712 * of semantics than just the native C++ type.
713 * @param tagName name of the searched element.
714 * @return Corresponding element value representation when it exists,
715 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
717 std::string gdcmDocument::GetEntryVRByName(TagName tagName) {
718 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
719 if( dictEntry == NULL)
722 gdcmDocEntry* elem = GetDocEntryByNumber(dictEntry->GetGroup(),
723 dictEntry->GetElement());
724 return elem->GetVR();
729 * \brief Searches within Header Entries (Dicom Elements) parsed with
730 * the public and private dictionaries
731 * for the element value representation of a given tag.
732 * @param group Group number of the searched tag.
733 * @param element Element number of the searched tag.
734 * @return Corresponding element value representation when it exists,
735 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
737 std::string gdcmDocument::GetEntryByNumber(guint16 group, guint16 element){
738 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
739 if ( ! tagHT.count(key))
741 return ((gdcmValEntry *)tagHT.find(key)->second)->GetValue();
745 * \brief Searches within Header Entries (Dicom Elements) parsed with
746 * the public and private dictionaries
747 * for the element value representation of a given tag..
749 * Obtaining the VR (Value Representation) might be needed by caller
750 * to convert the string typed content to caller's native type
751 * (think of C++ vs Python). The VR is actually of a higher level
752 * of semantics than just the native C++ type.
753 * @param group Group number of the searched tag.
754 * @param element Element number of the searched tag.
755 * @return Corresponding element value representation when it exists,
756 * and the string GDCM_UNFOUND ("gdcm::Unfound") otherwise.
758 std::string gdcmDocument::GetEntryVRByNumber(guint16 group, guint16 element) {
759 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
762 return elem->GetVR();
766 * \brief Searches within Header Entries (Dicom Elements) parsed with
767 * the public and private dictionaries
768 * for the value length of a given tag..
769 * @param group Group number of the searched tag.
770 * @param element Element number of the searched tag.
771 * @return Corresponding element length; -2 if not found
773 int gdcmDocument::GetEntryLengthByNumber(guint16 group, guint16 element) {
774 gdcmDocEntry* elem = GetDocEntryByNumber(group, element);
777 return elem->GetLength();
780 * \brief Sets the value (string) of the Header Entry (Dicom Element)
781 * @param content string value of the Dicom Element
782 * @param tagName name of the searched Dicom Element.
783 * @return true when found
785 bool gdcmDocument::SetEntryByName(std::string content,std::string tagName) {
786 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
787 if( dictEntry == NULL)
790 return SetEntryByNumber(content,dictEntry->GetGroup(),
791 dictEntry->GetElement());
795 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
796 * through it's (group, element) and modifies it's content with
798 * @param content new value (string) to substitute with
799 * @param group group number of the Dicom Element to modify
800 * @param element element number of the Dicom Element to modify
802 bool gdcmDocument::SetEntryByNumber(std::string content,
806 gdcmValEntry* ValEntry = GetValEntryByNumber(group, element);
809 dbg.Verbose(0, "gdcmDocument::SetEntryByNumber: no corresponding",
810 " ValEntry (try promotion first).");
814 // Non even content must be padded with a space (020H).
815 if((content.length())%2)
816 content = content + '\0';
818 ValEntry->SetValue(content);
820 // Integers have a special treatement for their length:
821 VRKey vr = ValEntry->GetVR();
822 if( (vr == "US") || (vr == "SS") )
823 ValEntry->SetLength(2);
824 else if( (vr == "UL") || (vr == "SL") )
825 ValEntry->SetLength(4);
827 ValEntry->SetLength(content.length());
833 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
834 * through it's (group, element) and modifies it's content with
836 * @param content new value (void *) to substitute with
837 * @param group group number of the Dicom Element to modify
838 * @param element element number of the Dicom Element to modify
840 bool gdcmDocument::SetEntryByNumber(void *content,
845 (void)lgth; //not used
846 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
847 if ( ! tagHT.count(key))
850 /* Hope Binray field length is never wrong
851 if(lgth%2) // Non even length are padded with a space (020H).
854 //content = content + '\0'; // fing a trick to enlarge a binary field?
858 a = (gdcmBinEntry *)tagHT[key];
859 a->SetVoidArea(content);
860 //a->SetLength(lgth); // ???
865 * \brief Accesses an existing gdcmDocEntry (i.e. a Dicom Element)
866 * in the PubDocEntrySet of this instance
867 * through it's (group, element) and modifies it's length with
869 * \warning Use with extreme caution.
870 * @param l new length to substitute with
871 * @param group group number of the Entry to modify
872 * @param element element number of the Entry to modify
873 * @return true on success, false otherwise.
875 bool gdcmDocument::SetEntryLengthByNumber(guint32 l,
879 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
880 if ( ! tagHT.count(key))
882 if (l%2) l++; // length must be even
883 ( ((tagHT.equal_range(key)).first)->second )->SetLength(l);
889 * \brief Gets (from Header) the offset of a 'non string' element value
890 * (LoadElementValues has already be executed)
891 * @param Group group number of the Entry
892 * @param Elem element number of the Entry
893 * @return File Offset of the Element Value
895 size_t gdcmDocument::GetEntryOffsetByNumber(guint16 Group, guint16 Elem)
897 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
900 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry present.");
903 return Entry->GetOffset();
907 * \brief Gets (from Header) a 'non string' element value
908 * (LoadElementValues has already be executed)
909 * @param Group group number of the Entry
910 * @param Elem element number of the Entry
911 * @return Pointer to the 'non string' area
913 void * gdcmDocument::GetEntryVoidAreaByNumber(guint16 Group, guint16 Elem)
915 gdcmDocEntry* Entry = GetDocEntryByNumber(Group, Elem);
918 dbg.Verbose(1, "gdcmDocument::GetDocEntryByNumber: no entry");
921 return ((gdcmBinEntry *)Entry)->GetVoidArea();
925 * \brief Loads (from disk) the element content
926 * when a string is not suitable
927 * @param Group group number of the Entry
928 * @param Elem element number of the Entry
930 void *gdcmDocument::LoadEntryVoidArea(guint16 Group, guint16 Elem)
932 gdcmDocEntry * Element= GetDocEntryByNumber(Group, Elem);
935 size_t o =(size_t)Element->GetOffset();
936 fseek(fp, o, SEEK_SET);
937 size_t l = Element->GetLength();
938 char* a = new char[l];
940 dbg.Verbose(0, "gdcmDocument::LoadEntryVoidArea cannot allocate a");
943 SetEntryVoidAreaByNumber(a, Group, Elem);
944 /// \todo check the result
945 size_t l2 = fread(a, 1, l ,fp);
956 * \brief Sets a 'non string' value to a given Dicom Element
957 * @param area area containing the 'non string' value
958 * @param group Group number of the searched Dicom Element
959 * @param element Element number of the searched Dicom Element
962 bool gdcmDocument::SetEntryVoidAreaByNumber(void * area,
966 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
967 if ( ! tagHT.count(key))
969 // This was for multimap ?
970 (( gdcmBinEntry *)( ((tagHT.equal_range(key)).first)->second ))->SetVoidArea(area);
976 * \brief Update the entries with the shadow dictionary.
977 * Only non even entries are analyzed
979 void gdcmDocument::UpdateShaEntries(void) {
980 //gdcmDictEntry *entry;
983 /// \todo TODO : still any use to explore recursively the whole structure?
985 for(ListTag::iterator it=listEntries.begin();
986 it!=listEntries.end();
989 // Odd group => from public dictionary
990 if((*it)->GetGroup()%2==0)
993 // Peer group => search the corresponding dict entry
995 entry=RefShaDict->GetDictEntryByNumber((*it)->GetGroup(),(*it)->GetElement());
999 if((*it)->IsImplicitVR())
1004 (*it)->SetValue(GetDocEntryUnvalue(*it)); // to go on compiling
1006 // Set the new entry and the new value
1007 (*it)->SetDictEntry(entry);
1008 CheckDocEntryVR(*it,vr);
1010 (*it)->SetValue(GetDocEntryValue(*it)); // to go on compiling
1015 // Remove precedent value transformation
1016 (*it)->SetDictEntry(NewVirtualDictEntry((*it)->GetGroup(),(*it)->GetElement(),vr));
1023 * \brief Searches within the Header Entries for a Dicom Element of
1025 * @param tagName name of the searched Dicom Element.
1026 * @return Corresponding Dicom Element when it exists, and NULL
1029 gdcmDocEntry *gdcmDocument::GetDocEntryByName(std::string tagName) {
1030 gdcmDictEntry *dictEntry = RefPubDict->GetDictEntryByName(tagName);
1031 if( dictEntry == NULL)
1034 return(GetDocEntryByNumber(dictEntry->GetGroup(),dictEntry->GetElement()));
1038 * \brief retrieves a Dicom Element (the first one) using (group, element)
1039 * \warning (group, element) IS NOT an identifier inside the Dicom Header
1040 * if you think it's NOT UNIQUE, check the count number
1041 * and use iterators to retrieve ALL the Dicoms Elements within
1042 * a given couple (group, element)
1043 * @param group Group number of the searched Dicom Element
1044 * @param element Element number of the searched Dicom Element
1047 gdcmDocEntry* gdcmDocument::GetDocEntryByNumber(guint16 group, guint16 element)
1049 TagKey key = gdcmDictEntry::TranslateToKey(group, element);
1050 if ( ! tagHT.count(key))
1052 return tagHT.find(key)->second;
1056 * \brief Same as \ref gdcmDocument::GetDocEntryByNumber except it only
1057 * returns a result when the corresponding entry is of type
1059 * @return When present, the corresponding ValEntry.
1061 gdcmValEntry* gdcmDocument::GetValEntryByNumber(guint16 group, guint16 element)
1063 gdcmDocEntry* CurrentEntry = GetDocEntryByNumber(group, element);
1065 return (gdcmValEntry*)0;
1066 if ( gdcmValEntry* ValEntry = dynamic_cast<gdcmValEntry*>(CurrentEntry) )
1070 dbg.Verbose(0, "gdcmDocument::GetValEntryByNumber: unfound ValEntry.");
1071 return (gdcmValEntry*)0;
1075 * \brief Loads the element while preserving the current
1076 * underlying file position indicator as opposed to
1077 * to LoadDocEntry that modifies it.
1078 * @param entry Header Entry whose value shall be loaded.
1081 void gdcmDocument::LoadDocEntrySafe(gdcmDocEntry * entry) {
1082 long PositionOnEntry = ftell(fp);
1083 LoadDocEntry(entry);
1084 fseek(fp, PositionOnEntry, SEEK_SET);
1088 * \brief Swaps back the bytes of 4-byte long integer accordingly to
1090 * @return The properly swaped 32 bits integer.
1092 guint32 gdcmDocument::SwapLong(guint32 a) {
1097 a=( ((a<<24) & 0xff000000) | ((a<<8) & 0x00ff0000) |
1098 ((a>>8) & 0x0000ff00) | ((a>>24) & 0x000000ff) );
1102 a=( ((a<<16) & 0xffff0000) | ((a>>16) & 0x0000ffff) );
1106 a=( ((a<<8) & 0xff00ff00) | ((a>>8) & 0x00ff00ff) );
1109 std::cout << "swapCode= " << sw << std::endl;
1110 dbg.Error(" gdcmDocument::SwapLong : unset swap code");
1117 * \brief Unswaps back the bytes of 4-byte long integer accordingly to
1119 * @return The properly unswaped 32 bits integer.
1121 guint32 gdcmDocument::UnswapLong(guint32 a) {
1122 return (SwapLong(a));
1126 * \brief Swaps the bytes so they agree with the processor order
1127 * @return The properly swaped 16 bits integer.
1129 guint16 gdcmDocument::SwapShort(guint16 a) {
1130 if ( (sw==4321) || (sw==2143) )
1131 a =(((a<<8) & 0x0ff00) | ((a>>8)&0x00ff));
1136 * \brief Unswaps the bytes so they agree with the processor order
1137 * @return The properly unswaped 16 bits integer.
1139 guint16 gdcmDocument::UnswapShort(guint16 a) {
1140 return (SwapShort(a));
1143 //-----------------------------------------------------------------------------
1147 * \brief Parses a DocEntrySet (Zero-level DocEntries or SQ Item DocEntries)
1148 * @return length of the parsed set.
1151 long gdcmDocument::ParseDES(gdcmDocEntrySet *set, long offset, long l_max, bool delim_mode) {
1153 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1154 gdcmValEntry *NewValEntry = (gdcmValEntry *)0;
1161 depth = set->GetDepthLevel();
1164 if ( !delim_mode && ftell(fp)-offset >= l_max) {
1167 NewDocEntry = ReadNextDocEntry( );
1171 vr = NewDocEntry->GetVR();
1175 if ( gdcmGlobal::GetVR()->IsVROfGdcmStringRepresentable(vr) )
1178 NewValEntry = new gdcmValEntry(NewDocEntry->GetDictEntry());
1179 NewValEntry->Copy(NewDocEntry);
1180 NewValEntry->SetDepthLevel(depth);
1181 set->AddEntry(NewValEntry);
1182 LoadDocEntry(NewValEntry);
1183 if (NewValEntry->isItemDelimitor())
1185 if ( !delim_mode && ftell(fp)-offset >= l_max)
1192 if ( ! gdcmGlobal::GetVR()->IsVROfGdcmBinaryRepresentable(vr) )
1194 ////// Neither ValEntry NOR BinEntry: should mean UNKOWN VR
1195 dbg.Verbose(0, "gdcmDocument::ParseDES: neither Valentry, "
1196 "nor BinEntry. Probably unknown VR.");
1199 ////// BinEntry or UNKOWN VR:
1200 bn = new gdcmBinEntry(NewDocEntry->GetDictEntry());
1201 bn->Copy(NewDocEntry);
1206 if (NewDocEntry->GetGroup() == 0x7fe0 &&
1207 NewDocEntry->GetElement() == 0x0010 )
1209 if (NewDocEntry->GetLength()==0xffffffff)
1210 // Broken US.3405.1.dcm
1211 Parse7FE0(); // to skip the pixels
1212 // (multipart JPEG/RLE are trouble makers)
1216 // to be sure we are at the beginning
1217 SkipToNextDocEntry(NewDocEntry);
1218 l = NewDocEntry->GetFullLength();
1224 l=NewDocEntry->GetReadLength();
1225 if (l != 0) // don't mess the delim_mode for zero-length sequence
1226 if (l == 0xffffffff)
1230 // no other way to create it ...
1231 sq = new gdcmSeqEntry(NewDocEntry->GetDictEntry(),
1232 set->GetDepthLevel());
1233 sq->Copy(NewDocEntry);
1234 sq->SetDelimitorMode(delim_mode);
1235 sq->SetDepthLevel(depth);
1238 { // Don't try to parse zero-length sequences
1239 long lgt = ParseSQ( sq,
1240 NewDocEntry->GetOffset(),
1242 (void)lgt; //not used...
1244 // FIXME : on en fait quoi, de lgt ?
1246 if ( !delim_mode && ftell(fp)-offset >= l_max)
1257 * \brief Parses a Sequence ( SeqEntry after SeqEntry)
1258 * @return parsed length for this level
1260 long gdcmDocument::ParseSQ(gdcmSeqEntry *set,
1261 long offset, long l_max, bool delim_mode)
1263 int SQItemNumber = 0;
1265 gdcmDocEntry *NewDocEntry = (gdcmDocEntry *)0;
1270 int depth = set->GetDepthLevel();
1271 (void)depth; //not used
1274 NewDocEntry = ReadNextDocEntry();
1276 if (NewDocEntry->isSequenceDelimitor()) {
1277 set->SetSequenceDelimitationItem(NewDocEntry);
1281 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1285 itemSQ = new gdcmSQItem(set->GetDepthLevel());
1286 itemSQ->AddEntry(NewDocEntry);
1287 l= NewDocEntry->GetReadLength();
1289 if (l == 0xffffffff)
1294 lgr=ParseDES(itemSQ, NewDocEntry->GetOffset(), l, dlm_mod);
1296 set->AddEntry(itemSQ,SQItemNumber);
1298 if (!delim_mode && (ftell(fp)-offset) >= l_max) {
1302 lgth = ftell(fp) - offset;
1307 * \brief Loads the element content if its length doesn't exceed
1308 * the value specified with gdcmDocument::SetMaxSizeLoadEntry()
1309 * @param Entry Header Entry (Dicom Element) to be dealt with
1311 void gdcmDocument::LoadDocEntry(gdcmDocEntry *Entry)
1314 guint16 group = Entry->GetGroup();
1315 std::string vr= Entry->GetVR();
1316 guint32 length = Entry->GetLength();
1318 fseek(fp, (long)Entry->GetOffset(), SEEK_SET);
1320 // A SeQuence "contains" a set of Elements.
1321 // (fffe e000) tells us an Element is beginning
1322 // (fffe e00d) tells us an Element just ended
1323 // (fffe e0dd) tells us the current SeQuence just ended
1324 if( group == 0xfffe ) {
1325 // NO more value field for SQ !
1329 // When the length is zero things are easy:
1330 if ( length == 0 ) {
1331 ((gdcmValEntry *)Entry)->SetValue("");
1335 // The elements whose length is bigger than the specified upper bound
1336 // are not loaded. Instead we leave a short notice of the offset of
1337 // the element content and it's length.
1339 if (length > MaxSizeLoadEntry) {
1340 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) )
1342 std::ostringstream s;
1343 s << "gdcm::NotLoaded (BinEntry)";
1344 s << " Address:" << (long)Entry->GetOffset();
1345 s << " Length:" << Entry->GetLength();
1346 s << " x(" << std::hex << Entry->GetLength() << ")";
1347 BinEntryPtr->SetValue(s.str());
1349 // to be sure we are at the end of the value ...
1350 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1352 // Be carefull : a BinEntry IS_A valEntry ...
1353 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1355 std::ostringstream s;
1356 s << "gdcm::NotLoaded. (ValEntry)";
1357 s << " Address:" << (long)Entry->GetOffset();
1358 s << " Length:" << Entry->GetLength();
1359 s << " x(" << std::hex << Entry->GetLength() << ")";
1360 ValEntryPtr->SetValue(s.str());
1362 // to be sure we are at the end of the value ...
1363 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1367 // When we find a BinEntry not very much can be done :
1368 if (gdcmBinEntry* BinEntryPtr = dynamic_cast< gdcmBinEntry* >(Entry) ) {
1369 LoadEntryVoidArea (BinEntryPtr->GetGroup(),BinEntryPtr->GetElement());
1374 // Any compacter code suggested (?)
1375 if ( IsDocEntryAnInteger(Entry) ) {
1377 std::ostringstream s;
1379 // When short integer(s) are expected, read and convert the following
1380 // n *two characters properly i.e. as short integers as opposed to strings.
1381 // Elements with Value Multiplicity > 1
1382 // contain a set of integers (not a single one)
1383 if (vr == "US" || vr == "SS") {
1385 NewInt = ReadInt16();
1388 for (int i=1; i < nbInt; i++) {
1390 NewInt = ReadInt16();
1395 // When integer(s) are expected, read and convert the following
1396 // n * four characters properly i.e. as integers as opposed to strings.
1397 // Elements with Value Multiplicity > 1
1398 // contain a set of integers (not a single one)
1399 else if (vr == "UL" || vr == "SL") {
1401 NewInt = ReadInt32();
1404 for (int i=1; i < nbInt; i++) {
1406 NewInt = ReadInt32();
1411 #ifdef GDCM_NO_ANSI_STRING_STREAM
1412 s << std::ends; // to avoid oddities on Solaris
1413 #endif //GDCM_NO_ANSI_STRING_STREAM
1415 ((gdcmValEntry *)Entry)->SetValue(s.str());
1419 // We need an additional byte for storing \0 that is not on disk
1420 std::string NewValue(length,0);
1421 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1422 if ( item_read != 1 ) {
1423 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1424 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1428 if( (vr == "UI") ) // Because of correspondance with the VR dic
1429 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1431 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1436 * \brief Find the value Length of the passed Header Entry
1437 * @param Entry Header Entry whose length of the value shall be loaded.
1439 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1440 guint16 element = Entry->GetElement();
1441 //guint16 group = Entry->GetGroup(); //FIXME
1442 std::string vr = Entry->GetVR();
1446 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1448 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1450 // The following reserved two bytes (see PS 3.5-2001, section
1451 // 7.1.2 Data element structure with explicit vr p27) must be
1452 // skipped before proceeding on reading the length on 4 bytes.
1453 fseek(fp, 2L, SEEK_CUR);
1454 guint32 length32 = ReadInt32();
1456 if ( (vr == "OB") && (length32 == 0xffffffff) )
1458 Entry->SetLength(FindDocEntryLengthOB());
1461 FixDocEntryFoundLength(Entry, length32);
1465 // Length is encoded on 2 bytes.
1466 length16 = ReadInt16();
1468 // We can tell the current file is encoded in big endian (like
1469 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1470 // and it's value is the one of the encoding of a big endian file.
1471 // In order to deal with such big endian encoded files, we have
1472 // (at least) two strategies:
1473 // * when we load the "Transfer Syntax" tag with value of big endian
1474 // encoding, we raise the proper flags. Then we wait for the end
1475 // of the META group (0x0002) among which is "Transfer Syntax",
1476 // before switching the swap code to big endian. We have to postpone
1477 // the switching of the swap code since the META group is fully encoded
1478 // in little endian, and big endian coding only starts at the next
1479 // group. The corresponding code can be hard to analyse and adds
1480 // many additional unnecessary tests for regular tags.
1481 // * the second strategy consists in waiting for trouble, that shall
1482 // appear when we find the first group with big endian encoding. This
1483 // is easy to detect since the length of a "Group Length" tag (the
1484 // ones with zero as element number) has to be of 4 (0x0004). When we
1485 // encounter 1024 (0x0400) chances are the encoding changed and we
1486 // found a group with big endian encoding.
1487 // We shall use this second strategy. In order to make sure that we
1488 // can interpret the presence of an apparently big endian encoded
1489 // length of a "Group Length" without committing a big mistake, we
1490 // add an additional check: we look in the already parsed elements
1491 // for the presence of a "Transfer Syntax" whose value has to be "big
1492 // endian encoding". When this is the case, chances are we have got our
1493 // hands on a big endian encoded file: we switch the swap code to
1494 // big endian and proceed...
1495 if ( (element == 0x0000) && (length16 == 0x0400) )
1497 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1499 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1504 SwitchSwapToBigEndian();
1505 // Restore the unproperly loaded values i.e. the group, the element
1506 // and the dictionary entry depending on them.
1507 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1508 guint16 CorrectElem = SwapShort(Entry->GetElement());
1509 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1513 // This correct tag is not in the dictionary. Create a new one.
1514 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1516 // FIXME this can create a memory leaks on the old entry that be
1517 // left unreferenced.
1518 Entry->SetDictEntry(NewTag);
1521 // Heuristic: well some files are really ill-formed.
1522 if ( length16 == 0xffff)
1525 //dbg.Verbose(0, "gdcmDocument::FindLength",
1526 // "Erroneous element length fixed.");
1527 // Actually, length= 0xffff means that we deal with
1528 // Unknown Sequence Length
1530 FixDocEntryFoundLength(Entry, (guint32)length16);
1535 // Either implicit VR or a non DICOM conformal (see note below) explicit
1536 // VR that ommited the VR of (at least) this element. Farts happen.
1537 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1538 // on Data elements "Implicit and Explicit VR Data Elements shall
1539 // not coexist in a Data Set and Data Sets nested within it".]
1540 // Length is on 4 bytes.
1542 FixDocEntryFoundLength(Entry, ReadInt32());
1548 * \brief Find the Value Representation of the current Dicom Element.
1551 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1553 if (Filetype != gdcmExplicitVR)
1558 long PositionOnEntry = ftell(fp);
1559 // Warning: we believe this is explicit VR (Value Representation) because
1560 // we used a heuristic that found "UL" in the first tag. Alas this
1561 // doesn't guarantee that all the tags will be in explicit VR. In some
1562 // cases (see e-film filtered files) one finds implicit VR tags mixed
1563 // within an explicit VR file. Hence we make sure the present tag
1564 // is in explicit VR and try to fix things if it happens not to be
1567 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1569 if(!CheckDocEntryVR(Entry,VR))
1571 fseek(fp, PositionOnEntry, SEEK_SET);
1572 // When this element is known in the dictionary we shall use, e.g. for
1573 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1574 // dictionary entry. Still we have to flag the element as implicit since
1575 // we know now our assumption on expliciteness is not furfilled.
1577 if ( Entry->IsVRUnknown() )
1578 Entry->SetVR("Implicit");
1579 Entry->SetImplicitVR();
1584 * \brief Check the correspondance between the VR of the header entry
1585 * and the taken VR. If they are different, the header entry is
1586 * updated with the new VR.
1587 * @param Entry Header Entry to check
1588 * @param vr Dicom Value Representation
1589 * @return false if the VR is incorrect of if the VR isn't referenced
1590 * otherwise, it returns true
1592 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1594 char msg[100]; // for sprintf
1595 bool RealExplicit = true;
1597 // Assume we are reading a falsely explicit VR file i.e. we reached
1598 // a tag where we expect reading a VR but are in fact we read the
1599 // first to bytes of the length. Then we will interogate (through find)
1600 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1601 // both GCC and VC++ implementations of the STL map. Hence when the
1602 // expected VR read happens to be non-ascii characters we consider
1603 // we hit falsely explicit VR tag.
1605 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1606 RealExplicit = false;
1608 // CLEANME searching the dicom_vr at each occurence is expensive.
1609 // PostPone this test in an optional integrity check at the end
1610 // of parsing or only in debug mode.
1611 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1612 RealExplicit= false;
1614 if ( !RealExplicit )
1616 // We thought this was explicit VR, but we end up with an
1617 // implicit VR tag. Let's backtrack.
1618 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1619 Entry->GetGroup(),Entry->GetElement());
1620 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1621 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1622 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1623 Entry->GetGroup(),Entry->GetElement(),
1624 "UL","FIXME","Group Length");
1625 Entry->SetDictEntry(NewEntry);
1630 if ( Entry->IsVRUnknown() )
1632 // When not a dictionary entry, we can safely overwrite the VR.
1633 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1639 else if ( Entry->GetVR() != vr )
1641 // The VR present in the file and the dictionary disagree. We assume
1642 // the file writer knew best and use the VR of the file. Since it would
1643 // be unwise to overwrite the VR of a dictionary (since it would
1644 // compromise it's next user), we need to clone the actual DictEntry
1645 // and change the VR for the read one.
1646 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1647 Entry->GetGroup(),Entry->GetElement(),
1648 vr,"FIXME",Entry->GetName());
1649 Entry->SetDictEntry(NewEntry);
1655 * \brief Get the transformed value of the header entry. The VR value
1656 * is used to define the transformation to operate on the value
1657 * \warning NOT end user intended method !
1659 * @return Transformed entry value
1661 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1663 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1665 std::string val=((gdcmValEntry *)Entry)->GetValue();
1666 std::string vr=Entry->GetVR();
1667 guint32 length = Entry->GetLength();
1668 std::ostringstream s;
1671 // When short integer(s) are expected, read and convert the following
1672 // n * 2 bytes properly i.e. as a multivaluated strings
1673 // (each single value is separated fromthe next one by '\'
1674 // as usual for standard multivaluated filels
1675 // Elements with Value Multiplicity > 1
1676 // contain a set of short integers (not a single one)
1678 if (vr == "US" || vr == "SS")
1683 for (int i=0; i < nbInt; i++)
1687 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1688 NewInt16 = SwapShort(NewInt16);
1693 // When integer(s) are expected, read and convert the following
1694 // n * 4 bytes properly i.e. as a multivaluated strings
1695 // (each single value is separated fromthe next one by '\'
1696 // as usual for standard multivaluated filels
1697 // Elements with Value Multiplicity > 1
1698 // contain a set of integers (not a single one)
1699 else if (vr == "UL" || vr == "SL")
1704 for (int i=0; i < nbInt; i++)
1708 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1709 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1710 NewInt32=SwapLong(NewInt32);
1714 #ifdef GDCM_NO_ANSI_STRING_STREAM
1715 s << std::ends; // to avoid oddities on Solaris
1716 #endif //GDCM_NO_ANSI_STRING_STREAM
1720 return(((gdcmValEntry *)Entry)->GetValue());
1724 * \brief Get the reverse transformed value of the header entry. The VR
1725 * value is used to define the reverse transformation to operate on
1727 * \warning NOT end user intended method !
1729 * @return Reverse transformed entry value
1731 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1733 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1735 std::string vr=Entry->GetVR();
1736 std::ostringstream s;
1737 std::vector<std::string> tokens;
1739 if (vr == "US" || vr == "SS")
1743 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1744 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1745 for (unsigned int i=0; i<tokens.size();i++)
1747 NewInt16 = atoi(tokens[i].c_str());
1748 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1752 if (vr == "UL" || vr == "SL")
1756 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1757 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1758 for (unsigned int i=0; i<tokens.size();i++)
1760 NewInt32 = atoi(tokens[i].c_str());
1761 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1762 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1767 #ifdef GDCM_NO_ANSI_STRING_STREAM
1768 s << std::ends; // to avoid oddities on Solaris
1769 #endif //GDCM_NO_ANSI_STRING_STREAM
1773 return(((gdcmValEntry *)Entry)->GetValue());
1777 * \brief Skip a given Header Entry
1778 * \warning NOT end user intended method !
1781 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1783 SkipBytes(entry->GetLength());
1787 * \brief Skips to the begining of the next Header Entry
1788 * \warning NOT end user intended method !
1791 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1793 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1794 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1798 * \brief When the length of an element value is obviously wrong (because
1799 * the parser went Jabberwocky) one can hope improving things by
1800 * applying some heuristics.
1802 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1803 guint32 FoundLength)
1805 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1806 if ( FoundLength == 0xffffffff) {
1810 guint16 gr =Entry->GetGroup();
1811 guint16 el =Entry->GetElement();
1813 if (FoundLength%2) {
1814 std::ostringstream s;
1815 s << "Warning : Tag with uneven length "
1817 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1818 dbg.Verbose(0, s.str().c_str());
1821 //////// Fix for some naughty General Electric images.
1822 // Allthough not recent many such GE corrupted images are still present
1823 // on Creatis hard disks. Hence this fix shall remain when such images
1824 // are no longer in user (we are talking a few years, here)...
1825 // Note: XMedCom probably uses such a trick since it is able to read
1826 // those pesky GE images ...
1827 if (FoundLength == 13) { // Only happens for this length !
1828 if ( (Entry->GetGroup() != 0x0008)
1829 || ( (Entry->GetElement() != 0x0070)
1830 && (Entry->GetElement() != 0x0080) ) )
1833 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1837 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1838 // Occurence of such images is quite low (unless one leaves close to a
1839 // 'Leonardo' source. Hence, one might consider commenting out the
1840 // following fix on efficiency reasons.
1842 if ( (Entry->GetGroup() == 0x0009)
1843 && ( (Entry->GetElement() == 0x1113)
1844 || (Entry->GetElement() == 0x1114) ) )
1847 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1850 //////// Deal with sequences, but only on users request:
1852 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1854 FoundLength = 0; // ReadLength is unchanged
1857 //////// We encountered a 'delimiter' element i.e. a tag of the form
1858 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1859 // taken into account.
1861 if(Entry->GetGroup() == 0xfffe)
1863 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1864 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1865 // causes extra troubles...
1866 if( Entry->GetElement() != 0x0000 )
1872 Entry->SetUsableLength(FoundLength);
1876 * \brief Apply some heuristics to predict whether the considered
1877 * element value contains/represents an integer or not.
1878 * @param Entry The element value on which to apply the predicate.
1879 * @return The result of the heuristical predicate.
1881 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1882 guint16 element = Entry->GetElement();
1883 guint16 group = Entry->GetGroup();
1884 std::string vr = Entry->GetVR();
1885 guint32 length = Entry->GetLength();
1887 // When we have some semantics on the element we just read, and if we
1888 // a priori know we are dealing with an integer, then we shall be
1889 // able to swap it's element value properly.
1890 if ( element == 0 ) // This is the group length of the group
1896 // Allthough this should never happen, still some images have a
1897 // corrupted group length [e.g. have a glance at offset x(8336) of
1898 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1899 // Since for dicom compliant and well behaved headers, the present
1900 // test is useless (and might even look a bit paranoid), when we
1901 // encounter such an ill-formed image, we simply display a warning
1902 // message and proceed on parsing (while crossing fingers).
1903 std::ostringstream s;
1904 int filePosition = ftell(fp);
1905 s << "Erroneous Group Length element length on : (" \
1906 << std::hex << group << " , " << element
1907 << ") -before- position x(" << filePosition << ")"
1908 << "lgt : " << length;
1909 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1913 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1920 * \brief Find the Length till the next sequence delimiter
1921 * \warning NOT end user intended method !
1925 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
1926 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1929 long PositionOnEntry = ftell(fp);
1930 bool FoundSequenceDelimiter = false;
1931 guint32 TotalLength = 0;
1934 while ( ! FoundSequenceDelimiter)
1940 TotalLength += 4; // We even have to decount the group and element
1942 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1944 char msg[100]; // for sprintf. Sorry
1945 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1946 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1950 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1951 FoundSequenceDelimiter = true;
1952 else if ( n != 0xe000 )
1954 char msg[100]; // for sprintf. Sorry
1955 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1957 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1961 ItemLength = ReadInt32();
1962 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1963 // the ItemLength with ReadInt32
1964 SkipBytes(ItemLength);
1966 fseek(fp, PositionOnEntry, SEEK_SET);
1971 * \brief Reads a supposed to be 16 Bits integer
1972 * (swaps it depending on processor endianity)
1973 * @return read value
1975 guint16 gdcmDocument::ReadInt16() {
1978 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1979 if ( item_read != 1 ) {
1981 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
1991 * \brief Reads a supposed to be 32 Bits integer
1992 * (swaps it depending on processor endianity)
1993 * @return read value
1995 guint32 gdcmDocument::ReadInt32() {
1998 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1999 if ( item_read != 1 ) {
2001 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2011 * \brief skips bytes inside the source file
2012 * \warning NOT end user intended method !
2015 void gdcmDocument::SkipBytes(guint32 NBytes) {
2016 //FIXME don't dump the returned value
2017 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2021 * \brief Loads all the needed Dictionaries
2022 * \warning NOT end user intended method !
2024 void gdcmDocument::Initialise(void)
2026 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2031 * \brief Discover what the swap code is (among little endian, big endian,
2032 * bad little endian, bad big endian).
2034 * @return false when we are absolutely sure
2035 * it's neither ACR-NEMA nor DICOM
2036 * true when we hope ours assuptions are OK
2038 bool gdcmDocument::CheckSwap() {
2040 // The only guaranted way of finding the swap code is to find a
2041 // group tag since we know it's length has to be of four bytes i.e.
2042 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2043 // occurs when we can't find such group...
2045 guint32 x=4; // x : for ntohs
2046 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2052 char deb[HEADER_LENGTH_TO_READ];
2054 // First, compare HostByteOrder and NetworkByteOrder in order to
2055 // determine if we shall need to swap bytes (i.e. the Endian type).
2061 // The easiest case is the one of a DICOM header, since it possesses a
2062 // file preamble where it suffice to look for the string "DICM".
2063 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2066 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2067 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2069 // Next, determine the value representation (VR). Let's skip to the
2070 // first element (0002, 0000) and check there if we find "UL"
2071 // - or "OB" if the 1st one is (0002,0001) -,
2072 // in which case we (almost) know it is explicit VR.
2073 // WARNING: if it happens to be implicit VR then what we will read
2074 // is the length of the group. If this ascii representation of this
2075 // length happens to be "UL" then we shall believe it is explicit VR.
2076 // FIXME: in order to fix the above warning, we could read the next
2077 // element value (or a couple of elements values) in order to make
2078 // sure we are not commiting a big mistake.
2079 // We need to skip :
2080 // * the 128 bytes of File Preamble (often padded with zeroes),
2081 // * the 4 bytes of "DICM" string,
2082 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2083 // i.e. a total of 136 bytes.
2087 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2088 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2089 // *Implicit* VR. -and it is !-
2091 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2092 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2093 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2094 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2095 // when Write DCM *adds*
2097 // Use gdcmDocument::dicom_vr to test all the possibilities
2098 // instead of just checking for UL, OB and UI !? group 0000
2100 Filetype = gdcmExplicitVR;
2101 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2102 "explicit Value Representation");
2106 Filetype = gdcmImplicitVR;
2107 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2108 "not an explicit Value Representation");
2114 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2115 "HostByteOrder != NetworkByteOrder");
2120 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2121 "HostByteOrder = NetworkByteOrder");
2124 // Position the file position indicator at first tag (i.e.
2125 // after the file preamble and the "DICM" string).
2127 fseek (fp, 132L, SEEK_SET);
2131 // Alas, this is not a DicomV3 file and whatever happens there is no file
2132 // preamble. We can reset the file position indicator to where the data
2133 // is (i.e. the beginning of the file).
2134 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2137 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2138 // By clean we mean that the length of the first tag is written down.
2139 // If this is the case and since the length of the first group HAS to be
2140 // four (bytes), then determining the proper swap code is straightforward.
2143 // We assume the array of char we are considering contains the binary
2144 // representation of a 32 bits integer. Hence the following dirty
2146 s32 = *((guint32 *)(entCur));
2167 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2168 // It is time for despaired wild guesses.
2169 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2170 // i.e. the 'group length' element is not present :
2172 // check the supposed to be 'group number'
2173 // 0x0002 or 0x0004 or 0x0008
2174 // to determine ' sw' value .
2175 // Only 0 or 4321 will be possible
2176 // (no oportunity to check for the formerly well known
2177 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2178 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2179 // the file IS NOT ACR-NEMA nor DICOM V3
2180 // Find a trick to tell it the caller...
2182 s16 = *((guint16 *)(deb));
2198 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2199 "ACR/NEMA unfound swap info (Really hopeless !)");
2200 Filetype = gdcmUnknown;
2204 // Then the only info we have is the net2host one.
2214 * \brief Restore the unproperly loaded values i.e. the group, the element
2215 * and the dictionary entry depending on them.
2217 void gdcmDocument::SwitchSwapToBigEndian(void)
2219 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2220 "Switching to BigEndian mode.");
2241 * \brief during parsing, Header Elements too long are not loaded in memory
2244 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2248 if ((guint32)NewSize >= (guint32)0xffffffff)
2250 MaxSizeLoadEntry = 0xffffffff;
2253 MaxSizeLoadEntry = NewSize;
2258 * \brief Header Elements too long will not be printed
2259 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2262 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2266 if ((guint32)NewSize >= (guint32)0xffffffff)
2268 MaxSizePrintEntry = 0xffffffff;
2271 MaxSizePrintEntry = NewSize;
2277 * \brief Read the next tag but WITHOUT loading it's value
2278 * (read the 'Group Number', the 'Element Number',
2279 * gets the Dict Entry
2280 * gets the VR, gets the length, gets the offset value)
2281 * @return On succes the newly created DocEntry, NULL on failure.
2283 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2285 gdcmDocEntry *NewEntry;
2290 // We reached the EOF (or an error occured) therefore
2291 // header parsing has to be considered as finished.
2292 return (gdcmDocEntry *)0;
2294 NewEntry = NewDocEntryByNumber(g, n);
2295 FindDocEntryVR(NewEntry);
2296 FindDocEntryLength(NewEntry);
2303 NewEntry->SetOffset(ftell(fp));
2309 * \brief Generate a free TagKey i.e. a TagKey that is not present
2310 * in the TagHt dictionary.
2311 * @param group The generated tag must belong to this group.
2312 * @return The element of tag with given group which is fee.
2314 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2316 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2318 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2319 if (tagHT.count(key) == 0)
2327 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2328 * is placed at the beginning of a tag (TestGroup, TestElement),
2329 * read the length associated to the Tag.
2330 * \warning On success the internal file pointer \ref gdcmDocument::fp
2331 * is modified to point after the tag and it's length.
2332 * On failure (i.e. when the tag wasn't the expected tag
2333 * (TestGroup, TestElement) the internal file pointer
2334 * \ref gdcmDocument::fp is restored to it's original position.
2335 * @param TestGroup The expected group of the tag.
2336 * @param TestElement The expected Element of the tag.
2337 * @return On success returns the length associated to the tag. On failure
2340 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2342 guint16 ItemTagGroup;
2343 guint16 ItemTagElement;
2344 long PositionOnEntry = ftell(fp);
2345 long CurrentPosition = ftell(fp); // On debugging purposes
2347 //// Read the Item Tag group and element, and make
2348 // sure they are respectively 0xfffe and 0xe000:
2349 ItemTagGroup = ReadInt16();
2350 ItemTagElement = ReadInt16();
2351 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2353 std::ostringstream s;
2354 s << " We should have found tag (";
2355 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2356 s << " but instead we encountered tag (";
2357 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2359 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2360 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2361 dbg.Verbose(0, s.str().c_str());
2362 fseek(fp, PositionOnEntry, SEEK_SET);
2366 //// Then read the associated Item Length
2367 CurrentPosition=ftell(fp);
2369 ItemLength = ReadInt32();
2371 std::ostringstream s;
2372 s << "Basic Item Length is: "
2373 << ItemLength << std::endl;
2374 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2375 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2381 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2382 * \sa \ref gdcmDocument::ReadTagLength
2383 * \warning See warning of \ref gdcmDocument::ReadTagLength
2384 * @return On success returns the length associated to the item tag.
2385 * On failure returns 0.
2387 guint32 gdcmDocument::ReadItemTagLength(void)
2389 return ReadTagLength(0xfffe, 0xe000);
2393 * \brief Read the length of an expected Sequence Delimiter tag i.e.
2395 * \sa \ref gdcmDocument::ReadTagLength
2396 * \warning See warning of \ref gdcmDocument::ReadTagLength
2397 * @return On success returns the length associated to the Sequence
2398 * Delimiter tag. On failure returns 0.
2400 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2402 return ReadTagLength(0xfffe, 0xe0dd);
2407 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2408 * No other way so 'skip' the Data
2412 void gdcmDocument::Parse7FE0 (void)
2414 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2418 if ( IsImplicitVRLittleEndianTransferSyntax()
2419 || IsExplicitVRLittleEndianTransferSyntax()
2420 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2421 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2424 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2426 //// Read the Basic Offset Table Item Tag length...
2427 guint32 ItemLength = ReadItemTagLength();
2429 //// ... and then read length[s] itself[themselves]. We don't use
2430 // the values read (BTW what is the purpous of those lengths ?)
2431 if (ItemLength != 0) {
2432 // BTW, what is the purpous of those length anyhow !?
2433 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2434 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2435 for (unsigned int i=0; i < ItemLength; i += 4){
2436 guint32 IndividualLength;
2437 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2438 std::ostringstream s;
2439 s << " Read one length: ";
2440 s << std::hex << IndividualLength << std::endl;
2441 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2445 if ( ! IsRLELossLessTransferSyntax() )
2449 //// We then skip (not reading them) all the fragments of images:
2450 while ( (ItemLength = ReadItemTagLength()) )
2452 SkipBytes(ItemLength);
2460 long RleSegmentLength[15], fragmentLength;
2462 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2463 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2465 // Parse fragments of the current Fragment (Frame)
2466 //------------------ scanning (not reading) fragment pixels
2467 guint32 nbRleSegments = ReadInt32();
2468 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2470 //// Reading RLE Segments Offset Table
2471 guint32 RleSegmentOffsetTable[15];
2472 for(int k=1; k<=15; k++) {
2474 RleSegmentOffsetTable[k] = ReadInt32();
2475 printf(" at : %x Offset Segment %d : %d (%x)\n",
2476 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2477 RleSegmentOffsetTable[k]);
2480 // skipping (not reading) RLE Segments
2481 if (nbRleSegments>1) {
2482 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2483 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2484 - RleSegmentOffsetTable[k];
2486 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2487 k,(unsigned)RleSegmentLength[k],
2488 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2489 SkipBytes(RleSegmentLength[k]);
2493 RleSegmentLength[nbRleSegments]= fragmentLength
2494 - RleSegmentOffsetTable[nbRleSegments];
2496 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2497 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2498 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2499 SkipBytes(RleSegmentLength[nbRleSegments]);
2507 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2508 * \warning Does NOT work with ACR-NEMA files
2509 * \todo Find a trick to solve the pb (use RET fields ?)
2511 * @return true if 'smaller'
2513 bool gdcmDocument::operator<(gdcmDocument &document)
2518 s1=this->GetEntryByNumber(0x0010,0x0010);
2519 s2=document.GetEntryByNumber(0x0010,0x0010);
2527 s1=this->GetEntryByNumber(0x0010,0x0020);
2528 s2=document.GetEntryByNumber(0x0010,0x0020);
2535 // Study Instance UID
2536 s1=this->GetEntryByNumber(0x0020,0x000d);
2537 s2=document.GetEntryByNumber(0x0020,0x000d);
2544 // Serie Instance UID
2545 s1=this->GetEntryByNumber(0x0020,0x000e);
2546 s2=document.GetEntryByNumber(0x0020,0x000e);
2558 //-----------------------------------------------------------------------------