1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2005/11/02 10:15:04 $
7 Version: $Revision: 1.299 $
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.html 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 =========================================================================*/
20 // -------------- Remember ! ----------------------------------
22 // Image Position (Patient) (0020,0032):
23 // If not found (ACR_NEMA) we try Image Position (0020,0030)
24 // If not found (ACR-NEMA), we consider Slice Location (0020,1041)
25 // or Location (0020,0050)
26 // as the Z coordinate,
27 // 0. for all the coordinates if nothing is found
29 // Image Position (Patient) (0020,0032) VM=3
31 // The attribute Patient Orientation (0020,0020) from the General Image Module
32 // is of type 2C and has the condition Required if image does not require
33 // Image Orientation (0020,0037) and Image Position (0020,0032).
34 // However, if the image does require the attributes
35 // - Image Orientation (Patient) (0020,0037), VM=6
36 // - Image Position (Patient) (0020,0032), VM=3
37 // then attribute Patient Orientation (0020,0020) should not be present
41 // Patient Position (0018,5100) values :
43 // HFS = Head First-Supine, where increasing (positive axis direction) :
44 // X -> to the direction pointed to by the patient's oustretched left arm
45 // Y -> to the anterior-to-posterior direction in the patient's body
46 // Z -> to the feet-to-head direction in the patient's body
48 // HFP = Head First-Prone, where increasing (positive axis direction) :
49 // X -> to the direction pointed to by the patient's oustretched left arm
50 // Y -> to the anterior-to-posterior direction in the patient's body
51 // Z -> to the feet-to-head direction in the patient's body
53 // FFS = Feet First-Supine, where increasing (positive axis direction) :
54 // X -> to the direction pointed to by the patient's oustretched left arm
55 // Y -> to the anterior-to-posterion direction in the patient's body
56 // Z -> to the feet-to-head direction in the patient's body
58 // FFP = Feet First-Prone, where increasing (positive axis direction) :
59 // X -> to the direction pointed to by the patient's oustretched left arm
60 // Y -> to the posterior-to-anterior direction in the patient's body
61 // Z -> to the feet-to-head direction in the patient's body
63 // HFDR = Head First-Decubitus Right
64 // HFDL = Head First-Decubitus Left
65 // FFDR = Feet First-Decubitus Right
66 // FFDL = Feet First-Decubitus Left
68 // we can also find (non standard!)
73 // CS 2 Patient Orientation (0020 0020)
74 // When the coordinates of the image
75 // are always present, this field is almost never used.
76 // Better we don't trust it too much ...
85 // (0020|0037) [Image Orientation (Patient)] [1\0\0\0\1\0 ]
88 // ---------------------------------------------------------------
91 #include "gdcmGlobal.h"
93 #include "gdcmDebug.h"
95 #include "gdcmSeqEntry.h"
96 #include "gdcmRLEFramesInfo.h"
97 #include "gdcmJPEGFragmentsInfo.h"
98 #include "gdcmDataEntry.h"
101 #include <stdio.h> //sscanf
102 #include <stdlib.h> // for atoi
107 //-----------------------------------------------------------------------------
108 // Constructor / Destructor
111 * \brief Constructor used when we want to generate dicom files from scratch
116 RLEInfo = new RLEFramesInfo;
117 JPEGInfo = new JPEGFragmentsInfo;
118 GrPixel = 0x7fe0; // to avoid further troubles
120 BasicOffsetTableItemValue = 0;
125 * \brief Canonical destructor.
133 delete[] BasicOffsetTableItemValue;
136 //-----------------------------------------------------------------------------
140 * @return false if file cannot be open or no swap info was found,
141 * or no tag was found.
145 if ( ! this->Document::Load( ) )
148 return DoTheLoadingJob( );
152 * \brief Does the Loading Job (internal use only)
153 * @return false if file cannot be open or no swap info was found,
154 * or no tag was found.
156 bool File::DoTheLoadingJob( )
159 // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
160 // We may encounter the 'RETired' (0x0028, 0x0200) tag
161 // (Image Location") . This entry contains the number of
162 // the group that contains the pixel data (hence the "Pixel Data"
163 // is found by indirection through the "Image Location").
164 // Inside the group pointed by "Image Location" the searched element
165 // is conventionally the element 0x0010 (when the norm is respected).
166 // When the "Image Location" is missing we default to group 0x7fe0.
167 // Note: this IS the right place for the code
170 const std::string &imgLocation = GetEntryString(0x0028, 0x0200);
171 if ( imgLocation == GDCM_UNFOUND )
178 GrPixel = (uint16_t) atoi( imgLocation.c_str() );
181 // sometimes Image Location value doesn't follow
182 // the supposed processor endianness.
183 // see gdcmData/cr172241.dcm
184 if ( GrPixel == 0xe07f )
189 if ( GrPixel != 0x7fe0 )
191 // This is a kludge for old dirty Philips imager.
199 // Now, we know GrPixel and NumPixel.
200 // Let's create a VirtualDictEntry to allow a further VR modification
201 // and force VR to match with BitsAllocated.
202 DocEntry *entry = GetDocEntry(GrPixel, NumPixel);
205 // Compute the RLE or JPEG info
207 const std::string &ts = GetTransferSyntax();
208 Fp->seekg( entry->GetOffset(), std::ios::beg );
209 if ( Global::GetTS()->IsRLELossless(ts) )
211 else if ( Global::GetTS()->IsJPEG(ts) )
212 ComputeJPEGFragmentInfo();
215 // Create a new DataEntry to change the DictEntry
216 // The changed DictEntry will have
217 // - a correct PixelVR OB or OW)
218 // - the name to "Pixel Data"
219 DataEntry *oldEntry = dynamic_cast<DataEntry *>(entry);
223 // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
224 // more than 8 (i.e 12, 16) is a 'O Words'
225 if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 )
230 // Change only made if usefull
231 if ( PixelVR != oldEntry->GetVR() )
233 DictEntry* newDict = DictEntry::New(GrPixel,NumPixel,
234 PixelVR,"1","Pixel Data");
236 DataEntry *newEntry = DataEntry::New(newDict);
238 newEntry->Copy(entry);
239 newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
240 oldEntry->SetSelfArea(false);
242 RemoveEntry(oldEntry);
251 * \brief This predicate, based on hopefully reasonable heuristics,
252 * decides whether or not the current File was properly parsed
253 * and contains the mandatory information for being considered as
254 * a well formed and usable Dicom/Acr File.
255 * @return true when File is the one of a reasonable Dicom/Acr file,
258 bool File::IsReadable()
260 if ( !Document::IsReadable() )
265 const std::string &res = GetEntryString(0x0028, 0x0005);
266 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
268 gdcmWarningMacro("Wrong Image Dimensions" << res);
269 return false; // Image Dimensions
271 bool b0028_0100 = true;
272 if ( !GetDocEntry(0x0028, 0x0100) )
274 gdcmWarningMacro("Bits Allocated (0028|0100) not found");
275 //return false; // "Bits Allocated"
278 bool b0028_0101 = true;
279 if ( !GetDocEntry(0x0028, 0x0101) )
281 gdcmWarningMacro("Bits Stored (0028|0101) not found");
282 //return false; // "Bits Stored"
285 bool b0028_0102 = true;
286 if ( !GetDocEntry(0x0028, 0x0102) )
288 gdcmWarningMacro("Hight Bit (0028|0102) not found");
289 //return false; // "High Bit"
292 bool b0028_0103 = true;
293 if ( !GetDocEntry(0x0028, 0x0103) )
295 gdcmWarningMacro("Pixel Representation (0028|0103) not found");
296 //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
300 if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
302 gdcmWarningMacro("Too much mandatory Tags missing !");
306 if ( !GetDocEntry(GrPixel, NumPixel) )
308 gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
309 GrPixel << "|" << NumPixel << "not found");
310 return false; // Pixel Dicom Element not found :-(
316 * \brief gets the info from 0020,0013 : Image Number else 0.
317 * @return image number
319 int File::GetImageNumber()
321 //0020 0013 : Image Number
322 std::string strImNumber = GetEntryString(0x0020,0x0013);
323 if ( strImNumber != GDCM_UNFOUND )
325 return atoi( strImNumber.c_str() );
331 * \brief gets the info from 0008,0060 : Modality
332 * @return Modality Type
334 ModalityType File::GetModality()
336 // 0008 0060 : Modality
337 std::string strModality = GetEntryString(0x0008,0x0060);
338 if ( strModality != GDCM_UNFOUND )
340 if ( strModality.find("AU") < strModality.length()) return AU;
341 else if ( strModality.find("AS") < strModality.length()) return AS;
342 else if ( strModality.find("BI") < strModality.length()) return BI;
343 else if ( strModality.find("CF") < strModality.length()) return CF;
344 else if ( strModality.find("CP") < strModality.length()) return CP;
345 else if ( strModality.find("CR") < strModality.length()) return CR;
346 else if ( strModality.find("CT") < strModality.length()) return CT;
347 else if ( strModality.find("CS") < strModality.length()) return CS;
348 else if ( strModality.find("DD") < strModality.length()) return DD;
349 else if ( strModality.find("DF") < strModality.length()) return DF;
350 else if ( strModality.find("DG") < strModality.length()) return DG;
351 else if ( strModality.find("DM") < strModality.length()) return DM;
352 else if ( strModality.find("DS") < strModality.length()) return DS;
353 else if ( strModality.find("DX") < strModality.length()) return DX;
354 else if ( strModality.find("ECG") < strModality.length()) return ECG;
355 else if ( strModality.find("EPS") < strModality.length()) return EPS;
356 else if ( strModality.find("FA") < strModality.length()) return FA;
357 else if ( strModality.find("FS") < strModality.length()) return FS;
358 else if ( strModality.find("HC") < strModality.length()) return HC;
359 else if ( strModality.find("HD") < strModality.length()) return HD;
360 else if ( strModality.find("LP") < strModality.length()) return LP;
361 else if ( strModality.find("LS") < strModality.length()) return LS;
362 else if ( strModality.find("MA") < strModality.length()) return MA;
363 else if ( strModality.find("MR") < strModality.length()) return MR;
364 else if ( strModality.find("NM") < strModality.length()) return NM;
365 else if ( strModality.find("OT") < strModality.length()) return OT;
366 else if ( strModality.find("PT") < strModality.length()) return PT;
367 else if ( strModality.find("RF") < strModality.length()) return RF;
368 else if ( strModality.find("RG") < strModality.length()) return RG;
369 else if ( strModality.find("RTDOSE")
370 < strModality.length()) return RTDOSE;
371 else if ( strModality.find("RTIMAGE")
372 < strModality.length()) return RTIMAGE;
373 else if ( strModality.find("RTPLAN")
374 < strModality.length()) return RTPLAN;
375 else if ( strModality.find("RTSTRUCT")
376 < strModality.length()) return RTSTRUCT;
377 else if ( strModality.find("SM") < strModality.length()) return SM;
378 else if ( strModality.find("ST") < strModality.length()) return ST;
379 else if ( strModality.find("TG") < strModality.length()) return TG;
380 else if ( strModality.find("US") < strModality.length()) return US;
381 else if ( strModality.find("VF") < strModality.length()) return VF;
382 else if ( strModality.find("XA") < strModality.length()) return XA;
383 else if ( strModality.find("XC") < strModality.length()) return XC;
387 /// \todo throw error return value ???
388 /// specified <> unknown in our database
396 * \brief Retrieve the number of columns of image.
397 * @return The encountered size when found, 0 by default.
398 * 0 means the file is NOT USABLE. The caller will have to check
402 DataEntry *entry = GetDataEntry(0x0028,0x0011);
404 return (int)entry->GetValue(0);
409 * \brief Retrieve the number of lines of image.
410 * \warning The defaulted value is 1 as opposed to File::GetXSize()
411 * @return The encountered size when found, 1 by default
412 * (The ACR-NEMA file contains a Signal, not an Image).
416 DataEntry *entry = GetDataEntry(0x0028,0x0010);
418 return (int)entry->GetValue(0);
425 // The Rows (0028,0010) entry was optional for ACR/NEMA.
426 // (at least some images didn't have it.)
427 // It might hence be a signal (1D image). So we default to 1:
432 * \brief Retrieve the number of planes of volume or the number
433 * of frames of a multiframe.
434 * \warning When present we consider the "Number of Frames" as the third
435 * dimension. When missing we consider the third dimension as
436 * being the ACR-NEMA "Planes" tag content.
437 * @return The encountered size when found, 1 by default (single image).
441 // Both DicomV3 and ACR/Nema consider the "Number of Frames"
442 // as the third dimension.
443 DataEntry *entry = GetDataEntry(0x0028,0x0008);
445 return (int)entry->GetValue(0);
447 // We then consider the "Planes" entry as the third dimension
448 entry = GetDataEntry(0x0028,0x0012);
450 return (int)entry->GetValue(0);
455 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
456 * then 0028,0030 : Pixel Spacing
458 * @return X dimension of a pixel
460 float File::GetXSpacing()
462 float xspacing = 1.0;
465 // To follow David Clunie's advice, we first check ImagerPixelSpacing
467 DataEntry *entry = GetDataEntry(0x0018,0x1164);
470 nbValue = entry->GetValueCount();
471 // Can't use IsValueCountValid because of the complex heuristic.
473 xspacing = (float)entry->GetValue(2);
475 xspacing = (float)entry->GetValue(1);
477 xspacing = (float)entry->GetValue(0);
479 if ( xspacing == 0.0 )
485 gdcmWarningMacro( "Unfound Imager Pixel Spacing (0018,1164)" );
488 entry = GetDataEntry(0x0028,0x0030);
491 nbValue = entry->GetValueCount();
493 xspacing = (float)entry->GetValue(2);
494 else if( nbValue >= 2 )
495 xspacing = (float)entry->GetValue(1);
497 xspacing = (float)entry->GetValue(0);
499 if ( xspacing == 0.0 )
505 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
512 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
513 * then from 0028,0030 : Pixel Spacing
515 * @return Y dimension of a pixel
517 float File::GetYSpacing()
519 float yspacing = 1.0;
520 // To follow David Clunie's advice, we first check ImagerPixelSpacing
522 DataEntry *entry = GetDataEntry(0x0018,0x1164);
525 yspacing = (float)entry->GetValue(0);
527 if ( yspacing == 0.0 )
533 gdcmWarningMacro( "Unfound Imager Pixel Spacing (0018,1164)" );
536 entry = GetDataEntry(0x0028,0x0030);
539 yspacing = (float)entry->GetValue(0);
541 if ( yspacing == 0.0 )
547 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
554 * \brief gets the info from 0018,0088 : Space Between Slices
555 * else from 0018,0050 : Slice Thickness
557 * @return Z dimension of a voxel-to be
559 float File::GetZSpacing()
564 // For *Dicom* images, ZSpacing should be calculated using
565 // XOrigin, YOrigin, ZOrigin (of the top left image corner)
566 // of 2 consecutive images, and the Orientation
568 // Computing ZSpacing on a single image is not really meaningfull !
570 float zspacing = 1.0f;
572 // Spacing Between Slices : distance between the middle of 2 slices
574 // jointives (Spacing between Slices = Slice Thickness)
575 // overlapping (Spacing between Slices < Slice Thickness)
576 // disjointes (Spacing between Slices > Slice Thickness)
577 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
578 // It only concerns the MRI guys, not people wanting to visualize volumes
579 // If Spacing Between Slices is missing,
580 // we suppose slices joint together
581 DataEntry *entry = GetDataEntry(0x0018,0x0088);
584 zspacing = (float)entry->GetValue(0);
586 if ( zspacing == 0.0 )
591 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
593 // if no 'Spacing Between Slices' is found,
594 // we assume slices join together
595 // (no overlapping, no interslice gap)
596 // if they don't, we're fucked up
597 entry = GetDataEntry(0x0018,0x0050);
600 zspacing = (float)entry->GetValue(0);
602 if ( zspacing == 0.0 )
607 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
613 * \brief gets the info from 0020,0032 : Image Position Patient
614 * else from 0020,0030 : Image Position (RET)
616 * @return up-left image corner X position
618 float File::GetXOrigin()
620 DataEntry *entry = GetDataEntry(0x0020,0x0032);
623 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
624 entry = GetDataEntry(0x0020,0x0030);
627 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
632 if( entry->GetValueCount() == 3 )
634 if (!entry->IsValueCountValid() )
636 gdcmErrorMacro( "Invalid Value Count" );
638 return (float)entry->GetValue(0);
644 * \brief gets the info from 0020,0032 : Image Position Patient
645 * else from 0020,0030 : Image Position (RET)
647 * @return up-left image corner Y position
649 float File::GetYOrigin()
651 DataEntry *entry = GetDataEntry(0x0020,0x0032);
654 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
655 entry = GetDataEntry(0x0020,0x0030);
658 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
663 if( entry->GetValueCount() == 3 )
665 if (!entry->IsValueCountValid() )
667 gdcmErrorMacro( "Invalid Value Count" );
669 return (float)entry->GetValue(1);
675 * \brief gets the info from 0020,0032 : Image Position Patient
676 * else from 0020,0030 : Image Position (RET)
677 * else from 0020,1041 : Slice Location
678 * else from 0020,0050 : Location
680 * @return up-left image corner Z position
682 float File::GetZOrigin()
684 DataEntry *entry = GetDataEntry(0x0020,0x0032);
687 if( entry->GetValueCount() == 3 )
689 if (!entry->IsValueCountValid() )
691 gdcmErrorMacro( "Invalid Value Count" );
693 return (float)entry->GetValue(2);
695 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
699 entry = GetDataEntry(0x0020,0x0030);
702 if( entry->GetValueCount() == 3 )
704 if (!entry->IsValueCountValid() )
706 gdcmErrorMacro( "Invalid Value Count" );
708 return (float)entry->GetValue(2);
710 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
714 // for *very* old ACR-NEMA images
715 entry = GetDataEntry(0x0020,0x1041);
718 if( entry->GetValueCount() == 1 )
720 if (!entry->IsValueCountValid() )
722 gdcmErrorMacro( "Invalid Value Count" );
724 return (float)entry->GetValue(0); // VM=1 !
726 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
730 entry = GetDataEntry(0x0020,0x0050);
733 if( entry->GetValueCount() == 1 )
735 if (!entry->IsValueCountValid() )
737 gdcmErrorMacro( "Invalid Value Count" );
739 return (float)entry->GetValue(0);
741 gdcmWarningMacro( "Wrong Location (0020,0050)");
744 return 0.; // Hopeless
748 * \brief gets the info from 0020,0037 : Image Orientation Patient
749 * or from 0020 0035 : Image Orientation (RET)
750 * (needed to organize DICOM files based on their x,y,z position)
751 * @param iop adress of the (6)float array to receive values
752 * @return true when one of the tag is found
753 * false when nothing is found
755 bool File::GetImageOrientationPatient( float iop[6] )
757 std::string strImOriPat;
758 //iop is supposed to be float[6]
759 iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
761 // 0020 0037 DS REL Image Orientation (Patient)
762 if ( (strImOriPat = GetEntryString(0x0020,0x0037)) != GDCM_UNFOUND )
764 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
765 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
767 gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037)."
768 << " Less than 6 values were found." );
773 // 0020 0035 DS REL Image Orientation (RET)
774 else if ( (strImOriPat = GetEntryString(0x0020,0x0035)) != GDCM_UNFOUND )
776 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
777 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
779 gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). "
780 << "Less than 6 values were found." );
788 * \brief Retrieve the number of Bits Stored (actually used)
789 * (as opposed to number of Bits Allocated)
790 * @return The encountered number of Bits Stored, 0 by default.
791 * 0 means the file is NOT USABLE. The caller has to check it !
793 int File::GetBitsStored()
795 DataEntry *entry = GetDataEntry(0x0028,0x0101);
798 gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
801 return (int)entry->GetValue(0);
805 * \brief Retrieve the number of Bits Allocated
806 * (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
807 * @return The encountered Number of Bits Allocated, 0 by default.
808 * 0 means the file is NOT USABLE. The caller has to check it !
810 int File::GetBitsAllocated()
812 DataEntry *entry = GetDataEntry(0x0028,0x0100);
815 gdcmWarningMacro("(0028,0100) is supposed to be mandatory");
818 return (int)entry->GetValue(0);
822 * \brief Retrieve the high bit position.
823 * \warning The method defaults to 0 when information is missing.
824 * The responsability of checking this value is left to the caller.
825 * @return The high bit position when present. 0 when missing.
827 int File::GetHighBitPosition()
829 DataEntry *entry = GetDataEntry(0x0028,0x0102);
832 gdcmWarningMacro("(0028,0102) is supposed to be mandatory");
835 return (int)entry->GetValue(0);
839 * \brief Retrieve the number of Samples Per Pixel
840 * (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
841 * @return The encountered number of Samples Per Pixel, 1 by default.
842 * (we assume Gray level Pixels)
844 int File::GetSamplesPerPixel()
846 DataEntry *entry = GetDataEntry(0x0028,0x0002);
849 gdcmWarningMacro("(0028,0002) is supposed to be mandatory");
850 return 1; // Well, it's supposed to be mandatory ...
851 // but sometimes it's missing : *we* assume Gray pixels
853 return (int)entry->GetValue(0);
857 * \brief Retrieve the Planar Configuration for RGB images
858 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
859 * @return The encountered Planar Configuration, 0 by default.
861 int File::GetPlanarConfiguration()
863 DataEntry *entry = GetDataEntry(0x0028,0x0006);
868 return (int)entry->GetValue(0);
872 * \brief Return the size (in bytes) of a single pixel of data.
873 * @return The size in bytes of a single pixel of data; 0 by default
874 * 0 means the file is NOT USABLE; the caller will have to check
876 int File::GetPixelSize()
878 // 0028 0100 US IMG Bits Allocated
879 // (in order no to be messed up by old ACR-NEMA RGB images)
880 assert( !(GetEntryString(0x0028,0x0100) == "24") );
882 std::string pixelType = GetPixelType();
883 if ( pixelType == "8U" || pixelType == "8S" )
887 if ( pixelType == "16U" || pixelType == "16S")
891 if ( pixelType == "32U" || pixelType == "32S")
895 if ( pixelType == "FD" )
899 gdcmWarningMacro( "Unknown pixel type: " << pixelType);
904 * \brief Build the Pixel Type of the image.
905 * Possible values are:
906 * - 8U unsigned 8 bit,
908 * - 16U unsigned 16 bit,
909 * - 16S signed 16 bit,
910 * - 32U unsigned 32 bit,
911 * - 32S signed 32 bit,
912 * - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
913 * \warning 12 bit images appear as 16 bit.
914 * 24 bit images appear as 8 bit + photochromatic interp ="RGB "
915 * + Planar Configuration = 0
916 * @return 0S if nothing found. NOT USABLE file. The caller has to check
918 std::string File::GetPixelType()
920 std::string bitsAlloc = GetEntryString(0x0028, 0x0100); // Bits Allocated
921 if ( bitsAlloc == GDCM_UNFOUND )
923 gdcmWarningMacro( "Missing Bits Allocated (0028,0100)");
924 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
927 if ( bitsAlloc == "64" )
931 else if ( bitsAlloc == "12" )
933 // It will be unpacked
936 else if ( bitsAlloc == "24" )
938 // (in order no to be messed up by old RGB images)
943 if( IsSignedPixelData() )
951 return bitsAlloc + sign;
955 * \brief Check whether the pixels are signed (1) or UNsigned (0) data.
956 * \warning The method defaults to false (UNsigned) when tag 0028|0103
958 * The responsability of checking this value is left to the caller
959 * (NO transformation is performed on the pixels to make then >0)
960 * @return True when signed, false when UNsigned
962 bool File::IsSignedPixelData()
964 DataEntry *entry = GetDataEntry(0x0028, 0x0103);//"Pixel Representation"
967 gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
970 return entry->GetValue(0) != 0;
974 * \brief Check whether this a monochrome picture (gray levels) or not,
975 * using "Photometric Interpretation" tag (0x0028,0x0004).
976 * @return true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
978 bool File::IsMonochrome()
980 const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
981 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
982 || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
986 if ( PhotometricInterp == GDCM_UNFOUND )
988 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
994 * \brief Check whether this a MONOCHROME1 picture (high values = dark)
995 * or not using "Photometric Interpretation" tag (0x0028,0x0004).
996 * @return true when "MONOCHROME1" . False otherwise.
998 bool File::IsMonochrome1()
1000 const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1001 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1005 if ( PhotometricInterp == GDCM_UNFOUND )
1007 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1013 * \brief Check whether this a "PALETTE COLOR" picture or not by accessing
1014 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1015 * @return true when "PALETTE COLOR". False otherwise.
1017 bool File::IsPaletteColor()
1019 std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1020 if ( PhotometricInterp == "PALETTE COLOR " )
1024 if ( PhotometricInterp == GDCM_UNFOUND )
1026 gdcmWarningMacro( "Not found : Palette color (0028,0004)");
1032 * \brief Check whether this a "YBR_FULL" color picture or not by accessing
1033 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1034 * @return true when "YBR_FULL". False otherwise.
1036 bool File::IsYBRFull()
1038 std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1039 if ( PhotometricInterp == "YBR_FULL" )
1043 if ( PhotometricInterp == GDCM_UNFOUND )
1045 gdcmWarningMacro( "Not found : YBR Full (0028,0004)");
1051 * \brief tells us if LUT are used
1052 * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1053 * are NOT considered as LUT, since nobody knows
1054 * how to deal with them
1055 * Please warn me if you know sbdy that *does* know ... jprx
1056 * @return true if LUT Descriptors and LUT Tables were found
1060 // Check the presence of the LUT Descriptors, and LUT Tables
1062 if ( !GetDocEntry(0x0028,0x1101) )
1066 // LutDescriptorGreen
1067 if ( !GetDocEntry(0x0028,0x1102) )
1071 // LutDescriptorBlue
1072 if ( !GetDocEntry(0x0028,0x1103) )
1076 // Red Palette Color Lookup Table Data
1077 if ( !GetDocEntry(0x0028,0x1201) )
1081 // Green Palette Color Lookup Table Data
1082 if ( !GetDocEntry(0x0028,0x1202) )
1086 // Blue Palette Color Lookup Table Data
1087 if ( !GetDocEntry(0x0028,0x1203) )
1092 // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1093 // NOT taken into account, but we don't know how to use it ...
1098 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1100 * @return Lookup Table number of Bits , 0 by default
1101 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1102 * @ return bit number of each LUT item
1104 int File::GetLUTNbits()
1106 std::vector<std::string> tokens;
1109 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1110 // = Lookup Table Desc-Blue
1111 // Consistency already checked in GetLUTLength
1112 std::string lutDescription = GetEntryString(0x0028,0x1101);
1113 if ( lutDescription == GDCM_UNFOUND )
1118 tokens.clear(); // clean any previous value
1119 Util::Tokenize ( lutDescription, tokens, "\\" );
1120 //LutLength=atoi(tokens[0].c_str());
1121 //LutDepth=atoi(tokens[1].c_str());
1123 lutNbits = atoi( tokens[2].c_str() );
1130 *\brief gets the info from 0028,1052 : Rescale Intercept
1131 * @return Rescale Intercept
1133 float File::GetRescaleIntercept()
1135 // 0028 1052 DS IMG Rescale Intercept
1136 DataEntry *entry = GetDataEntry(0x0028, 0x1052);
1139 gdcmWarningMacro( "Missing Rescale Intercept (0028,1052)");
1142 return (float)entry->GetValue(0);
1147 *\brief gets the info from 0028,1053 : Rescale Slope
1148 * @return Rescale Slope
1150 float File::GetRescaleSlope()
1152 // 0028 1053 DS IMG Rescale Slope
1153 DataEntry *entry = GetDataEntry(0x0028, 0x1053);
1156 gdcmWarningMacro( "Missing Rescale Slope (0028,1053)");
1159 return (float)entry->GetValue(0);
1163 * \brief This function is intended to user who doesn't want
1164 * to have to manage a LUT and expects to get an RBG Pixel image
1165 * (or a monochrome one ...)
1166 * \warning to be used with GetImagePixels()
1167 * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1169 int File::GetNumberOfScalarComponents()
1171 if ( GetSamplesPerPixel() == 3 )
1176 // 0028 0100 US IMG Bits Allocated
1177 // (in order no to be messed up by old RGB images)
1178 if ( GetEntryString(0x0028,0x0100) == "24" )
1183 std::string strPhotometricInterpretation = GetEntryString(0x0028,0x0004);
1185 if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1187 if ( HasLUT() )// PALETTE COLOR is NOT enough
1197 // beware of trailing space at end of string
1198 // DICOM tags are never of odd length
1199 if ( strPhotometricInterpretation == GDCM_UNFOUND ||
1200 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1201 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1207 // we assume that *all* kinds of YBR are dealt with
1213 * \brief This function is intended to user that DOESN'T want
1214 * to get RGB pixels image when it's stored as a PALETTE COLOR image
1215 * - the (vtk) user is supposed to know how deal with LUTs -
1216 * \warning to be used with GetImagePixelsRaw()
1217 * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1219 int File::GetNumberOfScalarComponentsRaw()
1221 // 0028 0100 US IMG Bits Allocated
1222 // (in order no to be messed up by old RGB images)
1223 if ( File::GetEntryString(0x0028,0x0100) == "24" )
1228 // we assume that *all* kinds of YBR are dealt with
1229 return GetSamplesPerPixel();
1233 * \brief Recover the offset (from the beginning of the file)
1234 * of *image* pixels (not *icone image* pixels, if any !)
1235 * @return Pixel Offset
1237 size_t File::GetPixelOffset()
1239 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1242 return pxlElement->GetOffset();
1246 gdcmDebugMacro( "Big trouble : Pixel Element ("
1247 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1253 * \brief Recover the pixel area length (in Bytes)
1254 * @return Pixel Element Length, as stored in the header
1255 * (NOT the memory space necessary to hold the Pixels
1256 * -in case of embeded compressed image-)
1257 * 0 : NOT USABLE file. The caller has to check.
1259 size_t File::GetPixelAreaLength()
1261 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1264 return pxlElement->GetLength();
1268 gdcmDebugMacro( "Big trouble : Pixel Element ("
1269 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1275 * \brief Adds the characteristics of a new element we want to anonymize
1276 * @param group Group number of the target tag.
1277 * @param elem Element number of the target tag.
1278 * @param value new value (string) to substitute with
1280 void File::AddAnonymizeElement (uint16_t group, uint16_t elem,
1281 std::string const &value)
1287 UserAnonymizeList.push_back(el);
1291 * \brief Overwrites in the file the values of the DicomElements
1294 void File::AnonymizeNoLoad()
1296 std::fstream *fp = new std::fstream(Filename.c_str(),
1297 std::ios::in | std::ios::out | std::ios::binary);
1301 uint32_t valLgth = 0;
1302 std::string *spaces;
1303 for (ListElements::iterator it = UserAnonymizeList.begin();
1304 it != UserAnonymizeList.end();
1307 d = GetDocEntry( (*it).Group, (*it).Elem);
1312 if ( dynamic_cast<SeqEntry *>(d) )
1314 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1318 offset = d->GetOffset();
1319 lgth = d->GetLength();
1322 spaces = new std::string( lgth-valLgth, ' ');
1323 (*it).Value = (*it).Value + *spaces;
1326 fp->seekp( offset, std::ios::beg );
1327 fp->write( (*it).Value.c_str(), lgth );
1335 * \brief anonymize a File (remove Patient's personal info passed with
1336 * AddAnonymizeElement()
1337 * \note You cannot Anonymize a DataEntry (to be fixed)
1339 bool File::AnonymizeFile()
1341 // If Anonymisation list is empty, let's perform some basic anonymization
1342 if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1344 // If exist, replace by spaces
1345 SetEntryString(" ",0x0010, 0x2154); // Telephone
1346 SetEntryString(" ",0x0010, 0x1040); // Adress
1347 SetEntryString(" ",0x0010, 0x0020); // Patient ID
1349 DocEntry *patientNameHE = GetDocEntry (0x0010, 0x0010);
1351 if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1353 std::string studyInstanceUID = GetEntryString (0x0020, 0x000d);
1354 if ( studyInstanceUID != GDCM_UNFOUND )
1356 SetEntryString(studyInstanceUID, 0x0010, 0x0010);
1360 SetEntryString("anonymized", 0x0010, 0x0010);
1367 for (ListElements::iterator it = UserAnonymizeList.begin();
1368 it != UserAnonymizeList.end();
1371 d = GetDocEntry( (*it).Group, (*it).Elem);
1376 if ( dynamic_cast<SeqEntry *>(d) )
1378 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1382 if ( dynamic_cast<DataEntry *>(d) )
1384 gdcmWarningMacro( "To 'Anonymize' a DataEntry, better use AnonymizeNoLoad (FIXME) ");
1388 SetEntryString ((*it).Value, (*it).Group, (*it).Elem);
1392 // In order to make definitively impossible any further identification
1393 // remove or replace all the stuff that contains a Date
1395 //0008 0012 DA ID Instance Creation Date
1396 //0008 0020 DA ID Study Date
1397 //0008 0021 DA ID Series Date
1398 //0008 0022 DA ID Acquisition Date
1399 //0008 0023 DA ID Content Date
1400 //0008 0024 DA ID Overlay Date
1401 //0008 0025 DA ID Curve Date
1402 //0008 002a DT ID Acquisition Datetime
1403 //0018 9074 DT ACQ Frame Acquisition Datetime
1404 //0018 9151 DT ACQ Frame Reference Datetime
1405 //0018 a002 DT ACQ Contribution Date Time
1406 //0020 3403 SH REL Modified Image Date (RET)
1407 //0032 0032 DA SDY Study Verified Date
1408 //0032 0034 DA SDY Study Read Date
1409 //0032 1000 DA SDY Scheduled Study Start Date
1410 //0032 1010 DA SDY Scheduled Study Stop Date
1411 //0032 1040 DA SDY Study Arrival Date
1412 //0032 1050 DA SDY Study Completion Date
1413 //0038 001a DA VIS Scheduled Admission Date
1414 //0038 001c DA VIS Scheduled Discharge Date
1415 //0038 0020 DA VIS Admitting Date
1416 //0038 0030 DA VIS Discharge Date
1417 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1418 //0040 0004 DA PRC Scheduled Procedure Step End Date
1419 //0040 0244 DA PRC Performed Procedure Step Start Date
1420 //0040 0250 DA PRC Performed Procedure Step End Date
1421 //0040 2004 DA PRC Issue Date of Imaging Service Request
1422 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1423 //0040 4011 DT PRC Expected Completion Date and Time
1424 //0040 a030 DT PRC Verification Date Time
1425 //0040 a032 DT PRC Observation Date Time
1426 //0040 a120 DT PRC DateTime
1427 //0040 a121 DA PRC Date
1428 //0040 a13a DT PRC Referenced Datetime
1429 //0070 0082 DA ??? Presentation Creation Date
1430 //0100 0420 DT ??? SOP Autorization Date and Time
1431 //0400 0105 DT ??? Digital Signature DateTime
1432 //2100 0040 DA PJ Creation Date
1433 //3006 0008 DA SSET Structure Set Date
1434 //3008 0024 DA ??? Treatment Control Point Date
1435 //3008 0054 DA ??? First Treatment Date
1436 //3008 0056 DA ??? Most Recent Treatment Date
1437 //3008 0162 DA ??? Safe Position Exit Date
1438 //3008 0166 DA ??? Safe Position Return Date
1439 //3008 0250 DA ??? Treatment Date
1440 //300a 0006 DA RT RT Plan Date
1441 //300a 022c DA RT Air Kerma Rate Reference Date
1442 //300e 0004 DA RT Review Date
1448 * \brief Performs some consistency checking on various 'File related'
1449 * (as opposed to 'DicomDir related') entries
1450 * then writes in a file all the (Dicom Elements) included the Pixels
1451 * @param fileName file name to write to
1452 * @param writetype type of the file to be written
1453 * (ACR, ExplicitVR, ImplicitVR)
1455 bool File::Write(std::string fileName, FileType writetype)
1457 std::ofstream *fp = new std::ofstream(fileName.c_str(),
1458 std::ios::out | std::ios::binary);
1461 gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1465 // Entry : 0002|0000 = group length -> recalculated
1466 DataEntry *e0000 = GetDataEntry(0x0002,0x0000);
1469 std::ostringstream sLen;
1470 sLen << ComputeGroup0002Length( );
1471 e0000->SetString(sLen.str());
1474 // Derma?.dcm does not have it...let's remove it FIXME FIXME
1475 if( writetype != JPEG )
1477 int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1480 // no (GrPixel, NumPixel) element
1481 std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1482 s_lgPix = Util::DicomString( s_lgPix.c_str() );
1483 InsertEntryString(s_lgPix,GrPixel, 0x0000);
1487 Document::WriteContent(fp, writetype);
1495 //-----------------------------------------------------------------------------
1499 //-----------------------------------------------------------------------------
1502 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1503 * Compute the RLE extra information and store it in \ref RLEInfo
1504 * for later pixel retrieval usage.
1506 void File::ComputeRLEInfo()
1508 std::string ts = GetTransferSyntax();
1509 if ( !Global::GetTS()->IsRLELossless(ts) )
1514 // Encoded pixel data: for the time being we are only concerned with
1515 // Jpeg or RLE Pixel data encodings.
1516 // As stated in PS 3.5-2003, section 8.2 p44:
1517 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1518 // value representation OB is used".
1519 // Hence we expect an OB value representation. Concerning OB VR,
1520 // the section PS 3.5-2003, section A.4.c p 58-59, states:
1521 // "For the Value Representations OB and OW, the encoding shall meet the
1522 // following specifications depending on the Data element tag:"
1524 // - the first item in the sequence of items before the encoded pixel
1525 // data stream shall be basic offset table item. The basic offset table
1526 // item value, however, is not required to be present"
1527 ReadEncapsulatedBasicOffsetTable();
1529 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1530 // Loop on the individual frame[s] and store the information
1531 // on the RLE fragments in a RLEFramesInfo.
1532 // Note: - when only a single frame is present, this is a
1534 // - when more than one frame are present, then we are in
1535 // the case of a multi-frame image.
1539 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1541 // Since we have read the basic offset table, let's check the value were correct
1542 // or else produce a warning:
1543 if ( BasicOffsetTableItemValue )
1545 // If a BasicOffsetTableItemValue was read
1546 uint32_t individualLength = BasicOffsetTableItemValue[i];
1547 assert( individualLength == sum ); // REMOVE that if this is a problem
1548 if( individualLength != sum )
1550 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght" );
1552 sum += frameLength + 8;
1555 // Parse the RLE Header and store the corresponding RLE Segment
1556 // Offset Table information on fragments of this current Frame.
1557 // Note that the fragment pixels themselves are not loaded
1558 // (but just skipped).
1559 long frameOffset = Fp->tellg();
1561 uint32_t nbRleSegments = ReadInt32();
1562 if ( nbRleSegments > 16 )
1564 // There should be at most 15 segments (refer to RLEFrame class)
1565 gdcmWarningMacro( "Too many segments.");
1568 uint32_t rleSegmentOffsetTable[16];
1569 for( int k = 1; k <= 15; k++ )
1571 rleSegmentOffsetTable[k] = ReadInt32();
1574 // Deduce from both RLE Header and frameLength
1575 // the fragment length, and again store this info
1576 // in a RLEFramesInfo.
1577 long rleSegmentLength[15];
1578 // skipping (not reading) RLE Segments
1579 if ( nbRleSegments > 1)
1581 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1583 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
1584 - rleSegmentOffsetTable[k];
1585 SkipBytes(rleSegmentLength[k]);
1589 rleSegmentLength[nbRleSegments] = frameLength
1590 - rleSegmentOffsetTable[nbRleSegments];
1591 SkipBytes(rleSegmentLength[nbRleSegments]);
1593 // Store the collected info
1594 RLEFrame *newFrame = new RLEFrame;
1595 newFrame->SetNumberOfFragments(nbRleSegments);
1596 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1598 newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1599 newFrame->SetLength(uk,rleSegmentLength[uk]);
1601 RLEInfo->AddFrame(newFrame);
1604 // Make sure that we encounter a 'Sequence Delimiter Item'
1605 // at the end of the item :
1606 if ( !ReadTag(0xfffe, 0xe0dd) )
1608 gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1613 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1614 * Compute the jpeg extra information (fragment[s] offset[s] and
1615 * length) and store it[them] in \ref JPEGInfo for later pixel
1618 void File::ComputeJPEGFragmentInfo()
1620 // If you need to, look for comments of ComputeRLEInfo().
1621 std::string ts = GetTransferSyntax();
1622 if ( ! Global::GetTS()->IsJPEG(ts) )
1627 ReadEncapsulatedBasicOffsetTable();
1629 // Loop on the fragments[s] and store the parsed information in a
1631 long fragmentLength;
1634 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1636 // Since we have read the basic offset table, let's check the value were correct
1637 // or else produce a warning:
1638 // A.4 Transfer syntaxes for encapsulation of encoded pixel data:
1639 // When the Item Value is present, the Basic Offset Table Item Value shall contain
1640 // concatenated 32-bit unsigned integer values that are byte offsets to the first
1641 // byte of the Item Tag of the first fragment for each frame in the Sequence of
1642 // Items. These offsets are measured from the first byte of the first Item Tag
1643 // following the Basic Offset Table item (See Table A.4-2).
1645 if ( BasicOffsetTableItemValue )
1647 // If a BasicOffsetTableItemValue was read
1648 uint32_t individualLength = BasicOffsetTableItemValue[i];
1649 //assert( individualLength == sum ); // Seems like 00191113.dcm is off by one ??
1650 if( individualLength != sum )
1652 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght:" <<
1653 individualLength << " != " << sum );
1655 sum += fragmentLength + 8;
1659 long fragmentOffset = Fp->tellg();
1660 // Store the collected info
1661 JPEGFragment *newFragment = new JPEGFragment;
1662 newFragment->SetOffset(fragmentOffset);
1663 newFragment->SetLength(fragmentLength);
1664 JPEGInfo->AddFragment(newFragment);
1666 SkipBytes(fragmentLength);
1669 // Make sure that we encounter a 'Sequence Delimiter Item'
1670 // at the end of the item :
1671 if ( !ReadTag(0xfffe, 0xe0dd) )
1673 gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1678 * \brief Assuming the internal file pointer \ref Document::Fp
1679 * is placed at the beginning of a tag, check whether this
1680 * tag is (TestGroup, TestElem).
1681 * \warning On success the internal file pointer \ref Document::Fp
1682 * is modified to point after the tag.
1683 * On failure (i.e. when the tag wasn't the expected tag
1684 * (TestGroup, TestElem) the internal file pointer
1685 * \ref Document::Fp is restored to it's original position.
1686 * @param testGroup The expected group of the tag.
1687 * @param testElem The expected Element of the tag.
1688 * @return True on success, false otherwise.
1690 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1692 long positionOnEntry = Fp->tellg();
1693 long currentPosition = Fp->tellg(); // On debugging purposes
1695 // Read the Item Tag group and element, and make
1696 // sure they are what we expected:
1697 uint16_t itemTagGroup;
1698 uint16_t itemTagElem;
1701 itemTagGroup = ReadInt16();
1702 itemTagElem = ReadInt16();
1704 catch ( FormatError )
1706 gdcmErrorMacro( "Can not read tag for "
1707 << " We should have found tag ("
1708 << DictEntry::TranslateToKey(testGroup,testElem) << ")"
1713 if ( itemTagGroup != testGroup || itemTagElem != testElem )
1715 // in order not to pollute output we don't warn on 'delimitors'
1716 if (itemTagGroup != 0xfffe || testGroup != 0xfffe )
1717 gdcmErrorMacro( "Wrong Item Tag found:"
1718 << " We should have found tag ("
1719 << DictEntry::TranslateToKey(testGroup,testElem) << ")" << std::endl
1720 << " but instead we encountered tag ("
1721 << DictEntry::TranslateToKey(itemTagGroup,itemTagElem) << ")"
1722 << " at address: " << " 0x(" << std::hex
1723 << (unsigned int)currentPosition << std::dec << ")"
1725 Fp->seekg(positionOnEntry, std::ios::beg);
1733 * \brief Assuming the internal file pointer \ref Document::Fp
1734 * is placed at the beginning of a tag (TestGroup, TestElement),
1735 * read the length associated to the Tag.
1736 * \warning On success the internal file pointer \ref Document::Fp
1737 * is modified to point after the tag and it's length.
1738 * On failure (i.e. when the tag wasn't the expected tag
1739 * (TestGroup, TestElement) the internal file pointer
1740 * \ref Document::Fp is restored to it's original position.
1741 * @param testGroup The expected Group of the tag.
1742 * @param testElem The expected Element of the tag.
1743 * @return On success returns the length associated to the tag. On failure
1746 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1749 if ( !ReadTag(testGroup, testElem) )
1751 // Avoid polutting output
1752 if ( testGroup != 0xfffe )
1753 gdcmErrorMacro( "ReadTag did not succeed for ("
1754 << DictEntry::TranslateToKey(testGroup,testElem)
1759 //// Then read the associated Item Length
1760 long currentPosition = Fp->tellg();
1761 uint32_t itemLength = ReadInt32();
1762 gdcmDebugMacro( "Basic Item Length is: " << itemLength
1763 << " at address: " << std::hex << (unsigned int)currentPosition);
1768 * \brief When parsing the Pixel Data of an encapsulated file, read
1769 * the basic offset table (when present, and BTW dump it).
1771 void File::ReadEncapsulatedBasicOffsetTable()
1773 //// Read the Basic Offset Table Item Tag length...
1774 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1776 // When present, read the basic offset table itself.
1777 // Notes: - since the presence of this basic offset table is optional
1778 // we can't rely on it for the implementation, and we will simply
1779 // trash it's content (when present).
1780 // - still, when present, we could add some further checks on the
1781 // lengths, but we won't bother with such fuses for the time being.
1782 if ( itemLength != 0 )
1784 char *charBasicOffsetTableItemValue = new char[itemLength];
1785 Fp->read(charBasicOffsetTableItemValue, itemLength);
1786 unsigned int nbEntries = itemLength/4;
1787 assert( nbEntries*4 == itemLength); // Make sure this is a multiple
1788 BasicOffsetTableItemValue = new uint32_t[nbEntries];
1790 for (unsigned int i=0; i < nbEntries; i++ )
1792 BasicOffsetTableItemValue[i] = *((uint32_t*)(&charBasicOffsetTableItemValue[4*i]));
1793 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1794 uint32_t val = BasicOffsetTableItemValue[i];
1795 BasicOffsetTableItemValue[i]
1796 = ( (val<<24) | ((val<<8) & 0x00ff0000) |
1797 ((val>>8) & 0x0000ff00) | (val>>24) );
1799 gdcmWarningMacro( "Read one length for: " <<
1800 std::hex << BasicOffsetTableItemValue[i] );
1803 delete[] charBasicOffsetTableItemValue;
1807 // These are the deprecated method that one day should be removed (after the next release)
1809 #ifndef GDCM_LEGACY_REMOVE
1811 * \ brief Loader. (DEPRECATED : temporaryly kept not to break the API)
1812 * @ param fileName file to be open for parsing
1813 * @ return false if file cannot be open or no swap info was found,
1814 * or no tag was found.
1815 * @ deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
1817 bool File::Load( std::string const &fileName )
1819 GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
1821 SetFileName( fileName );
1822 if ( ! this->Document::Load( ) )
1825 return DoTheLoadingJob( );
1829 //-----------------------------------------------------------------------------
1832 //-----------------------------------------------------------------------------
1833 } // end namespace gdcm