1 /*=========================================================================
4 Module: $RCSfile: gdcmDocument.cxx,v $
6 Date: $Date: 2004/06/22 14:07:05 $
7 Version: $Revision: 1.23 $
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 (/*!delim_mode && */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 !
1326 //Entry->SetValue("gdcm::Skipped");
1327 // appel recursif de Load Value
1328 // (meme pb que pour le parsing)
1332 // When the length is zero things are easy:
1333 if ( length == 0 ) {
1334 ((gdcmValEntry *)Entry)->SetValue("");
1338 // The elements whose length is bigger than the specified upper bound
1339 // are not loaded. Instead we leave a short notice of the offset of
1340 // the element content and it's length.
1341 if (length > MaxSizeLoadEntry) {
1342 if (gdcmValEntry* ValEntryPtr = dynamic_cast< gdcmValEntry* >(Entry) )
1344 std::ostringstream s;
1345 s << "gdcm::NotLoaded.";
1346 s << " Address:" << (long)Entry->GetOffset();
1347 s << " Length:" << Entry->GetLength();
1348 s << " x(" << std::hex << Entry->GetLength() << ")";
1349 ValEntryPtr->SetValue(s.str());
1351 // to be sure we are at the end of the value ...
1352 fseek(fp,(long)Entry->GetOffset()+(long)Entry->GetLength(),SEEK_SET);
1357 // Any compacter code suggested (?)
1358 if ( IsDocEntryAnInteger(Entry) ) {
1360 std::ostringstream s;
1362 // When short integer(s) are expected, read and convert the following
1363 // n *two characters properly i.e. as short integers as opposed to strings.
1364 // Elements with Value Multiplicity > 1
1365 // contain a set of integers (not a single one)
1366 if (vr == "US" || vr == "SS") {
1368 NewInt = ReadInt16();
1371 for (int i=1; i < nbInt; i++) {
1373 NewInt = ReadInt16();
1378 // When integer(s) are expected, read and convert the following
1379 // n * four characters properly i.e. as integers as opposed to strings.
1380 // Elements with Value Multiplicity > 1
1381 // contain a set of integers (not a single one)
1382 else if (vr == "UL" || vr == "SL") {
1384 NewInt = ReadInt32();
1387 for (int i=1; i < nbInt; i++) {
1389 NewInt = ReadInt32();
1394 #ifdef GDCM_NO_ANSI_STRING_STREAM
1395 s << std::ends; // to avoid oddities on Solaris
1396 #endif //GDCM_NO_ANSI_STRING_STREAM
1398 ((gdcmValEntry *)Entry)->SetValue(s.str());
1402 // We need an additional byte for storing \0 that is not on disk
1403 std::string NewValue(length,0);
1404 item_read = fread(&(NewValue[0]), (size_t)length, (size_t)1, fp);
1405 if ( item_read != 1 ) {
1406 dbg.Verbose(1, "gdcmDocument::LoadElementValue","unread element value");
1407 ((gdcmValEntry *)Entry)->SetValue("gdcm::UnRead");
1411 if( (vr == "UI") ) // Because of correspondance with the VR dic
1412 ((gdcmValEntry *)Entry)->SetValue(NewValue.c_str());
1414 ((gdcmValEntry *)Entry)->SetValue(NewValue);
1419 * \brief Find the value Length of the passed Header Entry
1420 * @param Entry Header Entry whose length of the value shall be loaded.
1422 void gdcmDocument::FindDocEntryLength (gdcmDocEntry *Entry) {
1423 guint16 element = Entry->GetElement();
1424 //guint16 group = Entry->GetGroup(); //FIXME
1425 std::string vr = Entry->GetVR();
1429 if ( (Filetype == gdcmExplicitVR) && (! Entry->IsImplicitVR()) )
1431 if ( (vr=="OB") || (vr=="OW") || (vr=="SQ") || (vr=="UN") )
1433 // The following reserved two bytes (see PS 3.5-2001, section
1434 // 7.1.2 Data element structure with explicit vr p27) must be
1435 // skipped before proceeding on reading the length on 4 bytes.
1436 fseek(fp, 2L, SEEK_CUR);
1437 guint32 length32 = ReadInt32();
1439 if ( (vr == "OB") && (length32 == 0xffffffff) )
1441 Entry->SetLength(FindDocEntryLengthOB());
1444 FixDocEntryFoundLength(Entry, length32);
1448 // Length is encoded on 2 bytes.
1449 length16 = ReadInt16();
1451 // We can tell the current file is encoded in big endian (like
1452 // Data/US-RGB-8-epicard) when we find the "Transfer Syntax" tag
1453 // and it's value is the one of the encoding of a big endian file.
1454 // In order to deal with such big endian encoded files, we have
1455 // (at least) two strategies:
1456 // * when we load the "Transfer Syntax" tag with value of big endian
1457 // encoding, we raise the proper flags. Then we wait for the end
1458 // of the META group (0x0002) among which is "Transfer Syntax",
1459 // before switching the swap code to big endian. We have to postpone
1460 // the switching of the swap code since the META group is fully encoded
1461 // in little endian, and big endian coding only starts at the next
1462 // group. The corresponding code can be hard to analyse and adds
1463 // many additional unnecessary tests for regular tags.
1464 // * the second strategy consists in waiting for trouble, that shall
1465 // appear when we find the first group with big endian encoding. This
1466 // is easy to detect since the length of a "Group Length" tag (the
1467 // ones with zero as element number) has to be of 4 (0x0004). When we
1468 // encounter 1024 (0x0400) chances are the encoding changed and we
1469 // found a group with big endian encoding.
1470 // We shall use this second strategy. In order to make sure that we
1471 // can interpret the presence of an apparently big endian encoded
1472 // length of a "Group Length" without committing a big mistake, we
1473 // add an additional check: we look in the already parsed elements
1474 // for the presence of a "Transfer Syntax" whose value has to be "big
1475 // endian encoding". When this is the case, chances are we have got our
1476 // hands on a big endian encoded file: we switch the swap code to
1477 // big endian and proceed...
1478 if ( (element == 0x0000) && (length16 == 0x0400) )
1480 if ( ! IsExplicitVRBigEndianTransferSyntax() )
1482 dbg.Verbose(0, "gdcmDocument::FindLength", "not explicit VR");
1487 SwitchSwapToBigEndian();
1488 // Restore the unproperly loaded values i.e. the group, the element
1489 // and the dictionary entry depending on them.
1490 guint16 CorrectGroup = SwapShort(Entry->GetGroup());
1491 guint16 CorrectElem = SwapShort(Entry->GetElement());
1492 gdcmDictEntry * NewTag = GetDictEntryByNumber(CorrectGroup,
1496 // This correct tag is not in the dictionary. Create a new one.
1497 NewTag = NewVirtualDictEntry(CorrectGroup, CorrectElem);
1499 // FIXME this can create a memory leaks on the old entry that be
1500 // left unreferenced.
1501 Entry->SetDictEntry(NewTag);
1504 // Heuristic: well some files are really ill-formed.
1505 if ( length16 == 0xffff)
1508 //dbg.Verbose(0, "gdcmDocument::FindLength",
1509 // "Erroneous element length fixed.");
1510 // Actually, length= 0xffff means that we deal with
1511 // Unknown Sequence Length
1513 FixDocEntryFoundLength(Entry, (guint32)length16);
1518 // Either implicit VR or a non DICOM conformal (see note below) explicit
1519 // VR that ommited the VR of (at least) this element. Farts happen.
1520 // [Note: according to the part 5, PS 3.5-2001, section 7.1 p25
1521 // on Data elements "Implicit and Explicit VR Data Elements shall
1522 // not coexist in a Data Set and Data Sets nested within it".]
1523 // Length is on 4 bytes.
1525 FixDocEntryFoundLength(Entry, ReadInt32());
1531 * \brief Find the Value Representation of the current Dicom Element.
1534 void gdcmDocument::FindDocEntryVR( gdcmDocEntry *Entry)
1536 if (Filetype != gdcmExplicitVR)
1541 long PositionOnEntry = ftell(fp);
1542 // Warning: we believe this is explicit VR (Value Representation) because
1543 // we used a heuristic that found "UL" in the first tag. Alas this
1544 // doesn't guarantee that all the tags will be in explicit VR. In some
1545 // cases (see e-film filtered files) one finds implicit VR tags mixed
1546 // within an explicit VR file. Hence we make sure the present tag
1547 // is in explicit VR and try to fix things if it happens not to be
1550 (void)fread (&VR, (size_t)2,(size_t)1, fp);
1552 if(!CheckDocEntryVR(Entry,VR))
1554 fseek(fp, PositionOnEntry, SEEK_SET);
1555 // When this element is known in the dictionary we shall use, e.g. for
1556 // the semantics (see the usage of IsAnInteger), the VR proposed by the
1557 // dictionary entry. Still we have to flag the element as implicit since
1558 // we know now our assumption on expliciteness is not furfilled.
1560 if ( Entry->IsVRUnknown() )
1561 Entry->SetVR("Implicit");
1562 Entry->SetImplicitVR();
1567 * \brief Check the correspondance between the VR of the header entry
1568 * and the taken VR. If they are different, the header entry is
1569 * updated with the new VR.
1570 * @param Entry Header Entry to check
1571 * @param vr Dicom Value Representation
1572 * @return false if the VR is incorrect of if the VR isn't referenced
1573 * otherwise, it returns true
1575 bool gdcmDocument::CheckDocEntryVR(gdcmDocEntry *Entry, VRKey vr)
1577 char msg[100]; // for sprintf
1578 bool RealExplicit = true;
1580 // Assume we are reading a falsely explicit VR file i.e. we reached
1581 // a tag where we expect reading a VR but are in fact we read the
1582 // first to bytes of the length. Then we will interogate (through find)
1583 // the dicom_vr dictionary with oddities like "\004\0" which crashes
1584 // both GCC and VC++ implementations of the STL map. Hence when the
1585 // expected VR read happens to be non-ascii characters we consider
1586 // we hit falsely explicit VR tag.
1588 if ( (!isalpha(vr[0])) && (!isalpha(vr[1])) )
1589 RealExplicit = false;
1591 // CLEANME searching the dicom_vr at each occurence is expensive.
1592 // PostPone this test in an optional integrity check at the end
1593 // of parsing or only in debug mode.
1594 if ( RealExplicit && !gdcmGlobal::GetVR()->Count(vr) )
1595 RealExplicit= false;
1597 if ( !RealExplicit )
1599 // We thought this was explicit VR, but we end up with an
1600 // implicit VR tag. Let's backtrack.
1601 sprintf(msg,"Falsely explicit vr file (%04x,%04x)\n",
1602 Entry->GetGroup(),Entry->GetElement());
1603 dbg.Verbose(1, "gdcmDocument::FindVR: ",msg);
1604 if (Entry->GetGroup()%2 && Entry->GetElement() == 0x0000) { // Group length is UL !
1605 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1606 Entry->GetGroup(),Entry->GetElement(),
1607 "UL","FIXME","Group Length");
1608 Entry->SetDictEntry(NewEntry);
1613 if ( Entry->IsVRUnknown() )
1615 // When not a dictionary entry, we can safely overwrite the VR.
1616 if (Entry->GetElement() == 0x0000) { // Group length is UL !
1622 else if ( Entry->GetVR() != vr )
1624 // The VR present in the file and the dictionary disagree. We assume
1625 // the file writer knew best and use the VR of the file. Since it would
1626 // be unwise to overwrite the VR of a dictionary (since it would
1627 // compromise it's next user), we need to clone the actual DictEntry
1628 // and change the VR for the read one.
1629 gdcmDictEntry* NewEntry = NewVirtualDictEntry(
1630 Entry->GetGroup(),Entry->GetElement(),
1631 vr,"FIXME",Entry->GetName());
1632 Entry->SetDictEntry(NewEntry);
1638 * \brief Get the transformed value of the header entry. The VR value
1639 * is used to define the transformation to operate on the value
1640 * \warning NOT end user intended method !
1642 * @return Transformed entry value
1644 std::string gdcmDocument::GetDocEntryValue(gdcmDocEntry *Entry)
1646 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1648 std::string val=((gdcmValEntry *)Entry)->GetValue();
1649 std::string vr=Entry->GetVR();
1650 guint32 length = Entry->GetLength();
1651 std::ostringstream s;
1654 // When short integer(s) are expected, read and convert the following
1655 // n * 2 bytes properly i.e. as a multivaluated strings
1656 // (each single value is separated fromthe next one by '\'
1657 // as usual for standard multivaluated filels
1658 // Elements with Value Multiplicity > 1
1659 // contain a set of short integers (not a single one)
1661 if (vr == "US" || vr == "SS")
1666 for (int i=0; i < nbInt; i++)
1670 NewInt16 = (val[2*i+0]&0xFF)+((val[2*i+1]&0xFF)<<8);
1671 NewInt16 = SwapShort(NewInt16);
1676 // When integer(s) are expected, read and convert the following
1677 // n * 4 bytes properly i.e. as a multivaluated strings
1678 // (each single value is separated fromthe next one by '\'
1679 // as usual for standard multivaluated filels
1680 // Elements with Value Multiplicity > 1
1681 // contain a set of integers (not a single one)
1682 else if (vr == "UL" || vr == "SL")
1687 for (int i=0; i < nbInt; i++)
1691 NewInt32= (val[4*i+0]&0xFF)+((val[4*i+1]&0xFF)<<8)+
1692 ((val[4*i+2]&0xFF)<<16)+((val[4*i+3]&0xFF)<<24);
1693 NewInt32=SwapLong(NewInt32);
1697 #ifdef GDCM_NO_ANSI_STRING_STREAM
1698 s << std::ends; // to avoid oddities on Solaris
1699 #endif //GDCM_NO_ANSI_STRING_STREAM
1703 return(((gdcmValEntry *)Entry)->GetValue());
1707 * \brief Get the reverse transformed value of the header entry. The VR
1708 * value is used to define the reverse transformation to operate on
1710 * \warning NOT end user intended method !
1712 * @return Reverse transformed entry value
1714 std::string gdcmDocument::GetDocEntryUnvalue(gdcmDocEntry *Entry)
1716 if ( (IsDocEntryAnInteger(Entry)) && (Entry->IsImplicitVR()) )
1718 std::string vr=Entry->GetVR();
1719 std::ostringstream s;
1720 std::vector<std::string> tokens;
1722 if (vr == "US" || vr == "SS")
1726 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1727 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1728 for (unsigned int i=0; i<tokens.size();i++)
1730 NewInt16 = atoi(tokens[i].c_str());
1731 s<<(NewInt16&0xFF)<<((NewInt16>>8)&0xFF);
1735 if (vr == "UL" || vr == "SL")
1739 tokens.erase(tokens.begin(),tokens.end()); // clean any previous value
1740 Tokenize (((gdcmValEntry *)Entry)->GetValue(), tokens, "\\");
1741 for (unsigned int i=0; i<tokens.size();i++)
1743 NewInt32 = atoi(tokens[i].c_str());
1744 s<<(char)(NewInt32&0xFF)<<(char)((NewInt32>>8)&0xFF)
1745 <<(char)((NewInt32>>16)&0xFF)<<(char)((NewInt32>>24)&0xFF);
1750 #ifdef GDCM_NO_ANSI_STRING_STREAM
1751 s << std::ends; // to avoid oddities on Solaris
1752 #endif //GDCM_NO_ANSI_STRING_STREAM
1756 return(((gdcmValEntry *)Entry)->GetValue());
1760 * \brief Skip a given Header Entry
1761 * \warning NOT end user intended method !
1764 void gdcmDocument::SkipDocEntry(gdcmDocEntry *entry)
1766 SkipBytes(entry->GetLength());
1770 * \brief Skips to the begining of the next Header Entry
1771 * \warning NOT end user intended method !
1774 void gdcmDocument::SkipToNextDocEntry(gdcmDocEntry *entry)
1776 (void)fseek(fp, (long)(entry->GetOffset()), SEEK_SET);
1777 (void)fseek(fp, (long)(entry->GetReadLength()), SEEK_CUR);
1781 * \brief Loads the value for a a given VLEntry
1782 * \warning NOT end user intended method !
1785 void gdcmDocument::LoadVLEntry(gdcmDocEntry *entry)
1787 //SkipBytes(entry->GetLength());
1788 LoadDocEntry(entry);
1791 * \brief When the length of an element value is obviously wrong (because
1792 * the parser went Jabberwocky) one can hope improving things by
1793 * applying some heuristics.
1795 void gdcmDocument::FixDocEntryFoundLength(gdcmDocEntry *Entry,
1796 guint32 FoundLength)
1798 Entry->SetReadLength(FoundLength); // will be updated only if a bug is found
1799 if ( FoundLength == 0xffffffff) {
1803 guint16 gr =Entry->GetGroup();
1804 guint16 el =Entry->GetElement();
1806 if (FoundLength%2) {
1807 std::ostringstream s;
1808 s << "Warning : Tag with uneven length "
1810 << " in x(" << std::hex << gr << "," << el <<")" << std::dec;
1811 dbg.Verbose(0, s.str().c_str());
1814 //////// Fix for some naughty General Electric images.
1815 // Allthough not recent many such GE corrupted images are still present
1816 // on Creatis hard disks. Hence this fix shall remain when such images
1817 // are no longer in user (we are talking a few years, here)...
1818 // Note: XMedCom probably uses such a trick since it is able to read
1819 // those pesky GE images ...
1820 if (FoundLength == 13) { // Only happens for this length !
1821 if ( (Entry->GetGroup() != 0x0008)
1822 || ( (Entry->GetElement() != 0x0070)
1823 && (Entry->GetElement() != 0x0080) ) )
1826 Entry->SetReadLength(10); /// \todo a bug is to be fixed !?
1830 //////// Fix for some brain-dead 'Leonardo' Siemens images.
1831 // Occurence of such images is quite low (unless one leaves close to a
1832 // 'Leonardo' source. Hence, one might consider commenting out the
1833 // following fix on efficiency reasons.
1835 if ( (Entry->GetGroup() == 0x0009)
1836 && ( (Entry->GetElement() == 0x1113)
1837 || (Entry->GetElement() == 0x1114) ) )
1840 Entry->SetReadLength(4); /// \todo a bug is to be fixed !?
1843 //////// Deal with sequences, but only on users request:
1845 if ( ( Entry->GetVR() == "SQ") && enableSequences)
1847 FoundLength = 0; // ReadLength is unchanged
1850 //////// We encountered a 'delimiter' element i.e. a tag of the form
1851 // "fffe|xxxx" which is just a marker. Delimiters length should not be
1852 // taken into account.
1854 if(Entry->GetGroup() == 0xfffe)
1856 // According to the norm, fffe|0000 shouldn't exist. BUT the Philips
1857 // image gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm happens to
1858 // causes extra troubles...
1859 if( Entry->GetElement() != 0x0000 )
1865 Entry->SetUsableLength(FoundLength);
1869 * \brief Apply some heuristics to predict whether the considered
1870 * element value contains/represents an integer or not.
1871 * @param Entry The element value on which to apply the predicate.
1872 * @return The result of the heuristical predicate.
1874 bool gdcmDocument::IsDocEntryAnInteger(gdcmDocEntry *Entry) {
1875 guint16 element = Entry->GetElement();
1876 guint16 group = Entry->GetGroup();
1877 std::string vr = Entry->GetVR();
1878 guint32 length = Entry->GetLength();
1880 // When we have some semantics on the element we just read, and if we
1881 // a priori know we are dealing with an integer, then we shall be
1882 // able to swap it's element value properly.
1883 if ( element == 0 ) // This is the group length of the group
1889 // Allthough this should never happen, still some images have a
1890 // corrupted group length [e.g. have a glance at offset x(8336) of
1891 // gdcmData/gdcm-MR-PHILIPS-16-Multi-Seq.dcm].
1892 // Since for dicom compliant and well behaved headers, the present
1893 // test is useless (and might even look a bit paranoid), when we
1894 // encounter such an ill-formed image, we simply display a warning
1895 // message and proceed on parsing (while crossing fingers).
1896 std::ostringstream s;
1897 int filePosition = ftell(fp);
1898 s << "Erroneous Group Length element length on : (" \
1899 << std::hex << group << " , " << element
1900 << ") -before- position x(" << filePosition << ")"
1901 << "lgt : " << length;
1902 dbg.Verbose(0, "gdcmDocument::IsDocEntryAnInteger", s.str().c_str() );
1906 if ( (vr == "UL") || (vr == "US") || (vr == "SL") || (vr == "SS") )
1913 * \brief Find the Length till the next sequence delimiter
1914 * \warning NOT end user intended method !
1918 guint32 gdcmDocument::FindDocEntryLengthOB(void) {
1919 // See PS 3.5-2001, section A.4 p. 49 on encapsulation of encoded pixel data.
1922 long PositionOnEntry = ftell(fp);
1923 bool FoundSequenceDelimiter = false;
1924 guint32 TotalLength = 0;
1927 while ( ! FoundSequenceDelimiter)
1933 TotalLength += 4; // We even have to decount the group and element
1935 if ( g != 0xfffe && g!=0xb00c ) //for bogus header
1937 char msg[100]; // for sprintf. Sorry
1938 sprintf(msg,"wrong group (%04x) for an item sequence (%04x,%04x)\n",g, g,n);
1939 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1943 if ( n == 0xe0dd || ( g==0xb00c && n==0x0eb6 ) ) // for bogus header
1944 FoundSequenceDelimiter = true;
1945 else if ( n != 0xe000 )
1947 char msg[100]; // for sprintf. Sorry
1948 sprintf(msg,"wrong element (%04x) for an item sequence (%04x,%04x)\n",
1950 dbg.Verbose(1, "gdcmDocument::FindLengthOB: ",msg);
1954 ItemLength = ReadInt32();
1955 TotalLength += ItemLength + 4; // We add 4 bytes since we just read
1956 // the ItemLength with ReadInt32
1957 SkipBytes(ItemLength);
1959 fseek(fp, PositionOnEntry, SEEK_SET);
1964 * \brief Reads a supposed to be 16 Bits integer
1965 * (swaps it depending on processor endianity)
1966 * @return read value
1968 guint16 gdcmDocument::ReadInt16() {
1971 item_read = fread (&g, (size_t)2,(size_t)1, fp);
1972 if ( item_read != 1 ) {
1974 dbg.Verbose(0, "gdcmDocument::ReadInt16", " File Error");
1984 * \brief Reads a supposed to be 32 Bits integer
1985 * (swaps it depending on processor endianity)
1986 * @return read value
1988 guint32 gdcmDocument::ReadInt32() {
1991 item_read = fread (&g, (size_t)4,(size_t)1, fp);
1992 if ( item_read != 1 ) {
1994 dbg.Verbose(0, "gdcmDocument::ReadInt32", " File Error");
2004 * \brief skips bytes inside the source file
2005 * \warning NOT end user intended method !
2008 void gdcmDocument::SkipBytes(guint32 NBytes) {
2009 //FIXME don't dump the returned value
2010 (void)fseek(fp, (long)NBytes, SEEK_CUR);
2014 * \brief Loads all the needed Dictionaries
2015 * \warning NOT end user intended method !
2017 void gdcmDocument::Initialise(void)
2019 RefPubDict = gdcmGlobal::GetDicts()->GetDefaultPubDict();
2024 * \brief Discover what the swap code is (among little endian, big endian,
2025 * bad little endian, bad big endian).
2027 * @return false when we are absolutely sure
2028 * it's neither ACR-NEMA nor DICOM
2029 * true when we hope ours assuptions are OK
2031 bool gdcmDocument::CheckSwap() {
2033 // The only guaranted way of finding the swap code is to find a
2034 // group tag since we know it's length has to be of four bytes i.e.
2035 // 0x00000004. Finding the swap code in then straigthforward. Trouble
2036 // occurs when we can't find such group...
2038 guint32 x=4; // x : for ntohs
2039 bool net2host; // true when HostByteOrder is the same as NetworkByteOrder
2045 char deb[HEADER_LENGTH_TO_READ];
2047 // First, compare HostByteOrder and NetworkByteOrder in order to
2048 // determine if we shall need to swap bytes (i.e. the Endian type).
2054 // The easiest case is the one of a DICOM header, since it possesses a
2055 // file preamble where it suffice to look for the string "DICM".
2056 lgrLue = fread(deb, 1, HEADER_LENGTH_TO_READ, fp);
2059 if(memcmp(entCur, "DICM", (size_t)4) == 0) {
2060 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "looks like DICOM Version3");
2062 // Next, determine the value representation (VR). Let's skip to the
2063 // first element (0002, 0000) and check there if we find "UL"
2064 // - or "OB" if the 1st one is (0002,0001) -,
2065 // in which case we (almost) know it is explicit VR.
2066 // WARNING: if it happens to be implicit VR then what we will read
2067 // is the length of the group. If this ascii representation of this
2068 // length happens to be "UL" then we shall believe it is explicit VR.
2069 // FIXME: in order to fix the above warning, we could read the next
2070 // element value (or a couple of elements values) in order to make
2071 // sure we are not commiting a big mistake.
2072 // We need to skip :
2073 // * the 128 bytes of File Preamble (often padded with zeroes),
2074 // * the 4 bytes of "DICM" string,
2075 // * the 4 bytes of the first tag (0002, 0000),or (0002, 0001)
2076 // i.e. a total of 136 bytes.
2080 // Sometimes (see : gdcmData/icone.dcm) group 0x0002 *is* Explicit VR,
2081 // but elem 0002,0010 (Transfert Syntax) tells us the file is
2082 // *Implicit* VR. -and it is !-
2084 if( (memcmp(entCur, "UL", (size_t)2) == 0) ||
2085 (memcmp(entCur, "OB", (size_t)2) == 0) ||
2086 (memcmp(entCur, "UI", (size_t)2) == 0) ||
2087 (memcmp(entCur, "CS", (size_t)2) == 0) ) // CS, to remove later
2088 // when Write DCM *adds*
2090 // Use gdcmDocument::dicom_vr to test all the possibilities
2091 // instead of just checking for UL, OB and UI !? group 0000
2093 Filetype = gdcmExplicitVR;
2094 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2095 "explicit Value Representation");
2099 Filetype = gdcmImplicitVR;
2100 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2101 "not an explicit Value Representation");
2107 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2108 "HostByteOrder != NetworkByteOrder");
2113 dbg.Verbose(1, "gdcmDocument::CheckSwap:",
2114 "HostByteOrder = NetworkByteOrder");
2117 // Position the file position indicator at first tag (i.e.
2118 // after the file preamble and the "DICM" string).
2120 fseek (fp, 132L, SEEK_SET);
2124 // Alas, this is not a DicomV3 file and whatever happens there is no file
2125 // preamble. We can reset the file position indicator to where the data
2126 // is (i.e. the beginning of the file).
2127 dbg.Verbose(1, "gdcmDocument::CheckSwap:", "not a DICOM Version3 file");
2130 // Our next best chance would be to be considering a 'clean' ACR/NEMA file.
2131 // By clean we mean that the length of the first tag is written down.
2132 // If this is the case and since the length of the first group HAS to be
2133 // four (bytes), then determining the proper swap code is straightforward.
2136 // We assume the array of char we are considering contains the binary
2137 // representation of a 32 bits integer. Hence the following dirty
2139 s32 = *((guint32 *)(entCur));
2160 // We are out of luck. It is not a DicomV3 nor a 'clean' ACR/NEMA file.
2161 // It is time for despaired wild guesses.
2162 // So, let's check if this file wouldn't happen to be 'dirty' ACR/NEMA,
2163 // i.e. the 'group length' element is not present :
2165 // check the supposed to be 'group number'
2166 // 0x0002 or 0x0004 or 0x0008
2167 // to determine ' sw' value .
2168 // Only 0 or 4321 will be possible
2169 // (no oportunity to check for the formerly well known
2170 // ACR-NEMA 'Bad Big Endian' or 'Bad Little Endian'
2171 // if unsuccessfull (i.e. neither 0x0002 nor 0x0200 etc -4, 8-)
2172 // the file IS NOT ACR-NEMA nor DICOM V3
2173 // Find a trick to tell it the caller...
2175 s16 = *((guint16 *)(deb));
2191 dbg.Verbose(0, "gdcmDocument::CheckSwap:",
2192 "ACR/NEMA unfound swap info (Really hopeless !)");
2193 Filetype = gdcmUnknown;
2197 // Then the only info we have is the net2host one.
2207 * \brief Restore the unproperly loaded values i.e. the group, the element
2208 * and the dictionary entry depending on them.
2210 void gdcmDocument::SwitchSwapToBigEndian(void)
2212 dbg.Verbose(1, "gdcmDocument::SwitchSwapToBigEndian",
2213 "Switching to BigEndian mode.");
2234 * \brief during parsing, Header Elements too long are not loaded in memory
2237 void gdcmDocument::SetMaxSizeLoadEntry(long NewSize)
2241 if ((guint32)NewSize >= (guint32)0xffffffff)
2243 MaxSizeLoadEntry = 0xffffffff;
2246 MaxSizeLoadEntry = NewSize;
2251 * \brief Header Elements too long will not be printed
2252 * \todo See comments of \ref gdcmDocument::MAX_SIZE_PRINT_ELEMENT_VALUE
2255 void gdcmDocument::SetMaxSizePrintEntry(long NewSize)
2259 if ((guint32)NewSize >= (guint32)0xffffffff)
2261 MaxSizePrintEntry = 0xffffffff;
2264 MaxSizePrintEntry = NewSize;
2270 * \brief Read the next tag but WITHOUT loading it's value
2271 * (read the 'Group Number', the 'Element Number',
2272 * gets the Dict Entry
2273 * gets the VR, gets the length, gets the offset value)
2274 * @return On succes the newly created DocEntry, NULL on failure.
2276 gdcmDocEntry *gdcmDocument::ReadNextDocEntry(void) {
2278 gdcmDocEntry *NewEntry;
2283 // We reached the EOF (or an error occured) therefore
2284 // header parsing has to be considered as finished.
2285 return (gdcmDocEntry *)0;
2287 NewEntry = NewDocEntryByNumber(g, n);
2288 FindDocEntryVR(NewEntry);
2289 FindDocEntryLength(NewEntry);
2296 NewEntry->SetOffset(ftell(fp));
2302 * \brief Generate a free TagKey i.e. a TagKey that is not present
2303 * in the TagHt dictionary.
2304 * @param group The generated tag must belong to this group.
2305 * @return The element of tag with given group which is fee.
2307 guint32 gdcmDocument::GenerateFreeTagKeyInGroup(guint16 group)
2309 for (guint32 elem = 0; elem < UINT32_MAX; elem++)
2311 TagKey key = gdcmDictEntry::TranslateToKey(group, elem);
2312 if (tagHT.count(key) == 0)
2320 * \brief Assuming the internal file pointer \ref gdcmDocument::fp
2321 * is placed at the beginning of a tag (TestGroup, TestElement),
2322 * read the length associated to the Tag.
2323 * \warning On success the internal file pointer \ref gdcmDocument::fp
2324 * is modified to point after the tag and it's length.
2325 * On failure (i.e. when the tag wasn't the expected tag
2326 * (TestGroup, TestElement) the internal file pointer
2327 * \ref gdcmDocument::fp is restored to it's original position.
2328 * @param TestGroup The expected group of the tag.
2329 * @param TestElement The expected Element of the tag.
2330 * @return On success returns the length associated to the tag. On failure
2333 guint32 gdcmDocument::ReadTagLength(guint16 TestGroup, guint16 TestElement)
2335 guint16 ItemTagGroup;
2336 guint16 ItemTagElement;
2337 long PositionOnEntry = ftell(fp);
2338 long CurrentPosition = ftell(fp); // On debugging purposes
2340 //// Read the Item Tag group and element, and make
2341 // sure they are respectively 0xfffe and 0xe000:
2342 ItemTagGroup = ReadInt16();
2343 ItemTagElement = ReadInt16();
2344 if ( (ItemTagGroup != TestGroup) || (ItemTagElement != TestElement ) )
2346 std::ostringstream s;
2347 s << " We should have found tag (";
2348 s << std::hex << TestGroup << "," << TestElement << ")" << std::endl;
2349 s << " but instead we encountered tag (";
2350 s << std::hex << ItemTagGroup << "," << ItemTagElement << ")"
2352 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2353 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: wrong Item Tag found:");
2354 dbg.Verbose(0, s.str().c_str());
2355 fseek(fp, PositionOnEntry, SEEK_SET);
2359 //// Then read the associated Item Length
2360 CurrentPosition=ftell(fp);
2362 ItemLength = ReadInt32();
2364 std::ostringstream s;
2365 s << "Basic Item Length is: "
2366 << ItemLength << std::endl;
2367 s << " at address: " << (unsigned)CurrentPosition << std::endl;
2368 dbg.Verbose(0, "gdcmDocument::ReadItemTagLength: ", s.str().c_str());
2374 * \brief Read the length of an exptected Item tag i.e. (0xfffe, 0xe000).
2375 * \sa \ref gdcmDocument::ReadTagLength
2376 * \warning See warning of \ref gdcmDocument::ReadTagLength
2377 * @return On success returns the length associated to the item tag.
2378 * On failure returns 0.
2380 guint32 gdcmDocument::ReadItemTagLength(void)
2382 return ReadTagLength(0xfffe, 0xe000);
2386 * \brief Read the length of an expected Sequence Delimiter tag i.e.
2388 * \sa \ref gdcmDocument::ReadTagLength
2389 * \warning See warning of \ref gdcmDocument::ReadTagLength
2390 * @return On success returns the length associated to the Sequence
2391 * Delimiter tag. On failure returns 0.
2393 guint32 gdcmDocument::ReadSequenceDelimiterTagLength(void)
2395 return ReadTagLength(0xfffe, 0xe0dd);
2400 * \brief Parse pixel data from disk for multi-fragment Jpeg/Rle files
2401 * No other way so 'skip' the Data
2405 void gdcmDocument::Parse7FE0 (void)
2407 gdcmDocEntry* Element = GetDocEntryByNumber(0x0002, 0x0010);
2411 if ( IsImplicitVRLittleEndianTransferSyntax()
2412 || IsExplicitVRLittleEndianTransferSyntax()
2413 || IsExplicitVRBigEndianTransferSyntax() /// \todo 1.2.2 ??? A verifier !
2414 || IsDeflatedExplicitVRLittleEndianTransferSyntax() )
2417 // ---------------- for Parsing : Position on begining of Jpeg/RLE Pixels
2419 //// Read the Basic Offset Table Item Tag length...
2420 guint32 ItemLength = ReadItemTagLength();
2422 //// ... and then read length[s] itself[themselves]. We don't use
2423 // the values read (BTW what is the purpous of those lengths ?)
2424 if (ItemLength != 0) {
2425 // BTW, what is the purpous of those length anyhow !?
2426 char * BasicOffsetTableItemValue = new char[ItemLength + 1];
2427 fread(BasicOffsetTableItemValue, ItemLength, 1, fp);
2428 for (unsigned int i=0; i < ItemLength; i += 4){
2429 guint32 IndividualLength;
2430 IndividualLength = str2num(&BasicOffsetTableItemValue[i],guint32);
2431 std::ostringstream s;
2432 s << " Read one length: ";
2433 s << std::hex << IndividualLength << std::endl;
2434 dbg.Verbose(0, "gdcmDocument::Parse7FE0: ", s.str().c_str());
2438 if ( ! IsRLELossLessTransferSyntax() )
2442 //// We then skip (not reading them) all the fragments of images:
2443 while ( (ItemLength = ReadItemTagLength()) )
2445 SkipBytes(ItemLength);
2453 long RleSegmentLength[15], fragmentLength;
2455 // while 'Sequence Delimiter Item' (fffe,e0dd) not found
2456 while ( (fragmentLength = ReadSequenceDelimiterTagLength()) )
2458 // Parse fragments of the current Fragment (Frame)
2459 //------------------ scanning (not reading) fragment pixels
2460 guint32 nbRleSegments = ReadInt32();
2461 printf(" Nb of RLE Segments : %d\n",nbRleSegments);
2463 //// Reading RLE Segments Offset Table
2464 guint32 RleSegmentOffsetTable[15];
2465 for(int k=1; k<=15; k++) {
2467 RleSegmentOffsetTable[k] = ReadInt32();
2468 printf(" at : %x Offset Segment %d : %d (%x)\n",
2469 (unsigned)ftellRes,k,RleSegmentOffsetTable[k],
2470 RleSegmentOffsetTable[k]);
2473 // skipping (not reading) RLE Segments
2474 if (nbRleSegments>1) {
2475 for(unsigned int k=1; k<=nbRleSegments-1; k++) {
2476 RleSegmentLength[k]= RleSegmentOffsetTable[k+1]
2477 - RleSegmentOffsetTable[k];
2479 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2480 k,(unsigned)RleSegmentLength[k],
2481 (unsigned)RleSegmentLength[k], (unsigned)ftellRes);
2482 SkipBytes(RleSegmentLength[k]);
2486 RleSegmentLength[nbRleSegments]= fragmentLength
2487 - RleSegmentOffsetTable[nbRleSegments];
2489 printf (" Segment %d : Length = %d x(%x) Start at %x\n",
2490 nbRleSegments,(unsigned)RleSegmentLength[nbRleSegments],
2491 (unsigned)RleSegmentLength[nbRleSegments],(unsigned)ftellRes);
2492 SkipBytes(RleSegmentLength[nbRleSegments]);
2500 * \brief Compares two documents, according to \ref gdcmDicomDir rules
2501 * \warning Does NOT work with ACR-NEMA files
2502 * \todo Find a trick to solve the pb (use RET fields ?)
2504 * @return true if 'smaller'
2506 bool gdcmDocument::operator<(gdcmDocument &document)
2511 s1=this->GetEntryByNumber(0x0010,0x0010);
2512 s2=document.GetEntryByNumber(0x0010,0x0010);
2520 s1=this->GetEntryByNumber(0x0010,0x0020);
2521 s2=document.GetEntryByNumber(0x0010,0x0020);
2528 // Study Instance UID
2529 s1=this->GetEntryByNumber(0x0020,0x000d);
2530 s2=document.GetEntryByNumber(0x0020,0x000d);
2537 // Serie Instance UID
2538 s1=this->GetEntryByNumber(0x0020,0x000e);
2539 s2=document.GetEntryByNumber(0x0020,0x000e);
2551 //-----------------------------------------------------------------------------