1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2005/12/15 13:36:55 $
7 Version: $Revision: 1.312 $
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( )
158 // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
159 // We may encounter the 'RETired' (0x0028, 0x0200) tag
160 // (Image Location") . This entry contains the number of
161 // the group that contains the pixel data (hence the "Pixel Data"
162 // is found by indirection through the "Image Location").
163 // Inside the group pointed by "Image Location" the searched element
164 // is conventionally the element 0x0010 (when the norm is respected).
165 // When the "Image Location" is missing we default to group 0x7fe0.
166 // Note: this IS the right place for the code
169 const std::string &imgLocation = GetEntryString(0x0028, 0x0200);
170 if ( imgLocation == GDCM_UNFOUND )
177 GrPixel = (uint16_t) atoi( imgLocation.c_str() );
180 // sometimes Image Location value doesn't follow
181 // the supposed processor endianness.
182 // see gdcmData/cr172241.dcm
183 if ( GrPixel == 0xe07f )
188 if ( GrPixel != 0x7fe0 )
190 // This is a kludge for old dirty Philips imager.
198 // Now, we know GrPixel and NumPixel.
199 // Let's create a VirtualDictEntry to allow a further VR modification
200 // and force VR to match with BitsAllocated.
201 DocEntry *entry = GetDocEntry(GrPixel, NumPixel);
204 // Compute the RLE or JPEG info
206 const std::string &ts = GetTransferSyntax();
207 Fp->seekg( entry->GetOffset(), std::ios::beg );
208 if ( Global::GetTS()->IsRLELossless(ts) )
210 else if ( Global::GetTS()->IsJPEG(ts) )
211 ComputeJPEGFragmentInfo();
214 // Create a new DataEntry to change the DictEntry
215 // The changed DictEntry will have
216 // - a correct PixelVR OB or OW)
217 // - the name to "Pixel Data"
218 DataEntry *oldEntry = dynamic_cast<DataEntry *>(entry);
222 // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
223 // more than 8 (i.e 12, 16) is a 'O Words'
224 if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 )
229 // Change only made if usefull
230 if ( PixelVR != oldEntry->GetVR() )
232 DictEntry* newDict = DictEntry::New(GrPixel,NumPixel,
233 PixelVR,"1","Pixel Data");
235 DataEntry *newEntry = DataEntry::New(newDict);
237 newEntry->Copy(entry);
238 newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
239 oldEntry->SetSelfArea(false);
241 RemoveEntry(oldEntry);
250 * \brief This predicate, based on hopefully reasonable heuristics,
251 * decides whether or not the current File was properly parsed
252 * and contains the mandatory information for being considered as
253 * a well formed and usable Dicom/Acr File.
254 * @return true when File is the one of a reasonable Dicom/Acr file,
257 bool File::IsReadable()
259 if ( !Document::IsReadable() )
264 const std::string &res = GetEntryString(0x0028, 0x0005);
265 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
267 gdcmWarningMacro("Wrong Image Dimensions" << res);
268 return false; // Image Dimensions
270 bool b0028_0100 = true;
271 if ( !GetDocEntry(0x0028, 0x0100) )
273 gdcmWarningMacro("Bits Allocated (0028|0100) not found");
274 //return false; // "Bits Allocated"
277 bool b0028_0101 = true;
278 if ( !GetDocEntry(0x0028, 0x0101) )
280 gdcmWarningMacro("Bits Stored (0028|0101) not found");
281 //return false; // "Bits Stored"
284 bool b0028_0102 = true;
285 if ( !GetDocEntry(0x0028, 0x0102) )
287 gdcmWarningMacro("Hight Bit (0028|0102) not found");
288 //return false; // "High Bit"
291 bool b0028_0103 = true;
292 if ( !GetDocEntry(0x0028, 0x0103) )
294 gdcmWarningMacro("Pixel Representation (0028|0103) not found");
295 //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
299 if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
301 gdcmWarningMacro("Too much mandatory Tags missing !");
305 if ( !GetDocEntry(GrPixel, NumPixel) )
307 gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
308 GrPixel << "|" << NumPixel << "not found");
309 return false; // Pixel Dicom Element not found :-(
315 * \brief gets the info from 0020,0013 : Image Number else 0.
316 * @return image number
318 int File::GetImageNumber()
320 //0020 0013 : Image Number
321 std::string strImNumber = GetEntryString(0x0020,0x0013);
322 if ( strImNumber != GDCM_UNFOUND )
324 return atoi( strImNumber.c_str() );
330 * \brief gets the info from 0008,0060 : Modality
331 * @return Modality Type
333 ModalityType File::GetModality()
335 // 0008 0060 : Modality
336 std::string strModality = GetEntryString(0x0008,0x0060);
337 if ( strModality != GDCM_UNFOUND )
339 if ( strModality.find("AU") < strModality.length()) return AU;
340 else if ( strModality.find("AS") < strModality.length()) return AS;
341 else if ( strModality.find("BI") < strModality.length()) return BI;
342 else if ( strModality.find("CF") < strModality.length()) return CF;
343 else if ( strModality.find("CP") < strModality.length()) return CP;
344 else if ( strModality.find("CR") < strModality.length()) return CR;
345 else if ( strModality.find("CT") < strModality.length()) return CT;
346 else if ( strModality.find("CS") < strModality.length()) return CS;
347 else if ( strModality.find("DD") < strModality.length()) return DD;
348 else if ( strModality.find("DF") < strModality.length()) return DF;
349 else if ( strModality.find("DG") < strModality.length()) return DG;
350 else if ( strModality.find("DM") < strModality.length()) return DM;
351 else if ( strModality.find("DS") < strModality.length()) return DS;
352 else if ( strModality.find("DX") < strModality.length()) return DX;
353 else if ( strModality.find("ECG") < strModality.length()) return ECG;
354 else if ( strModality.find("EPS") < strModality.length()) return EPS;
355 else if ( strModality.find("FA") < strModality.length()) return FA;
356 else if ( strModality.find("FS") < strModality.length()) return FS;
357 else if ( strModality.find("HC") < strModality.length()) return HC;
358 else if ( strModality.find("HD") < strModality.length()) return HD;
359 else if ( strModality.find("LP") < strModality.length()) return LP;
360 else if ( strModality.find("LS") < strModality.length()) return LS;
361 else if ( strModality.find("MA") < strModality.length()) return MA;
362 else if ( strModality.find("MR") < strModality.length()) return MR;
363 else if ( strModality.find("NM") < strModality.length()) return NM;
364 else if ( strModality.find("OT") < strModality.length()) return OT;
365 else if ( strModality.find("PT") < strModality.length()) return PT;
366 else if ( strModality.find("RF") < strModality.length()) return RF;
367 else if ( strModality.find("RG") < strModality.length()) return RG;
368 else if ( strModality.find("RTDOSE")
369 < strModality.length()) return RTDOSE;
370 else if ( strModality.find("RTIMAGE")
371 < strModality.length()) return RTIMAGE;
372 else if ( strModality.find("RTPLAN")
373 < strModality.length()) return RTPLAN;
374 else if ( strModality.find("RTSTRUCT")
375 < strModality.length()) return RTSTRUCT;
376 else if ( strModality.find("SM") < strModality.length()) return SM;
377 else if ( strModality.find("ST") < strModality.length()) return ST;
378 else if ( strModality.find("TG") < strModality.length()) return TG;
379 else if ( strModality.find("US") < strModality.length()) return US;
380 else if ( strModality.find("VF") < strModality.length()) return VF;
381 else if ( strModality.find("XA") < strModality.length()) return XA;
382 else if ( strModality.find("XC") < strModality.length()) return XC;
386 /// \todo throw error return value ???
387 /// specified <> unknown in our database
395 * \brief Retrieve the number of columns of image.
396 * @return The encountered size when found, 0 by default.
397 * 0 means the file is NOT USABLE. The caller will have to check
401 DataEntry *entry = GetDataEntry(0x0028,0x0011);
403 return (int)entry->GetValue(0);
408 * \brief Retrieve the number of lines of image.
409 * \warning The defaulted value is 1 as opposed to File::GetXSize()
410 * @return The encountered size when found, 1 by default
411 * (The ACR-NEMA file contains a Signal, not an Image).
415 DataEntry *entry = GetDataEntry(0x0028,0x0010);
417 return (int)entry->GetValue(0);
424 // The Rows (0028,0010) entry was optional for ACR/NEMA.
425 // (at least some images didn't have it.)
426 // It might hence be a signal (1D image). So we default to 1:
431 * \brief Retrieve the number of planes of volume or the number
432 * of frames of a multiframe.
433 * \warning When present we consider the "Number of Frames" as the third
434 * dimension. When missing we consider the third dimension as
435 * being the ACR-NEMA "Planes" tag content.
436 * @return The encountered size when found, 1 by default (single image).
440 // Both DicomV3 and ACR/Nema consider the "Number of Frames"
441 // as the third dimension.
442 DataEntry *entry = GetDataEntry(0x0028,0x0008);
444 return (int)entry->GetValue(0);
446 // We then consider the "Planes" entry as the third dimension
447 entry = GetDataEntry(0x0028,0x0012);
449 return (int)entry->GetValue(0);
454 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
455 * then 0028,0030 : Pixel Spacing
457 * @return X dimension of a pixel
459 float File::GetXSpacing()
461 float xspacing = 1.0;
464 // To follow David Clunie's advice, we first check ImagerPixelSpacing
466 DataEntry *entry = GetDataEntry(0x0018,0x1164);
469 nbValue = entry->GetValueCount();
470 // Can't use IsValueCountValid because of the complex heuristic.
472 gdcmWarningMacro("ImagerPixelSpacing (0x0018,0x1164) "
473 << "has a wrong number of values :" << nbValue);
476 xspacing = (float)entry->GetValue(2);
477 else if( nbValue >= 2 )
478 xspacing = (float)entry->GetValue(1);
480 xspacing = (float)entry->GetValue(0);
482 if ( xspacing == 0.0 )
488 gdcmWarningMacro( "Unfound Imager Pixel Spacing (0018,1164)" );
491 entry = GetDataEntry(0x0028,0x0030);
494 nbValue = entry->GetValueCount();
496 gdcmWarningMacro("PixelSpacing (0x0018,0x0030) "
497 << "has a wrong number of values :" << nbValue);
500 xspacing = (float)entry->GetValue(2);
501 else if( nbValue >= 2 )
502 xspacing = (float)entry->GetValue(1);
504 xspacing = (float)entry->GetValue(0);
506 if ( xspacing == 0.0 )
512 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
519 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
520 * then from 0028,0030 : Pixel Spacing
522 * @return Y dimension of a pixel
524 float File::GetYSpacing()
526 float yspacing = 1.0;
527 // To follow David Clunie's advice, we first check ImagerPixelSpacing
529 DataEntry *entry = GetDataEntry(0x0018,0x1164);
532 yspacing = (float)entry->GetValue(0);
534 if ( yspacing == 0.0 )
540 gdcmWarningMacro( "Unfound Imager Pixel Spacing (0018,1164)" );
543 entry = GetDataEntry(0x0028,0x0030);
546 yspacing = (float)entry->GetValue(0);
548 if ( yspacing == 0.0 )
554 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
561 * \brief gets the info from 0018,0088 : Space Between Slices
562 * else from 0018,0050 : Slice Thickness
565 * When an element is missing, we suppose slices join together
566 * (no overlapping, no interslice gap) but we have no way to check it !
567 * For *Dicom* images, ZSpacing *should be* calculated using
568 * XOrigin, YOrigin, ZOrigin (of the top left image corner)
569 * of 2 consecutive images, and the Orientation
570 * Computing ZSpacing on a single image is not really meaningfull !
572 * @return Z dimension of a voxel-to be
574 float File::GetZSpacing()
577 float zspacing = 1.0f;
579 // Spacing Between Slices : distance between the middle of 2 slices
581 // jointives (Spacing between Slices = Slice Thickness)
582 // overlapping (Spacing between Slices < Slice Thickness)
583 // disjointes (Spacing between Slices > Slice Thickness)
584 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
585 // It only concerns the MRI guys, not people wanting to visualize volumes
586 // If Spacing Between Slices is missing,
587 // we suppose slices joint together
588 DataEntry *entry = GetDataEntry(0x0018,0x0088);
591 zspacing = (float)entry->GetValue(0);
593 if ( zspacing == 0.0 )
598 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
600 // if no 'Spacing Between Slices' is found,
601 // we assume slices join together
602 // (no overlapping, no interslice gap)
603 entry = GetDataEntry(0x0018,0x0050);
606 zspacing = (float)entry->GetValue(0);
608 if ( zspacing == 0.0 )
613 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
615 // if no 'Spacing Between Slices' is found,
616 // we assume slices join together
617 // (no overlapping, no interslice gap)
618 entry = GetDataEntry(0x3004,0x000c);
621 float z1 = (float)entry->GetValue(0);
622 float z2 = (float)entry->GetValue(1);
623 zspacing = z2 - z1; // can be negative...
625 if ( zspacing == 0.0 )
634 * \brief gets the info from 0020,0032 : Image Position Patient
635 * else from 0020,0030 : Image Position (RET)
637 * @return up-left image corner X position
639 float File::GetXOrigin()
641 DataEntry *entry = GetDataEntry(0x0020,0x0032);
644 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
645 entry = GetDataEntry(0x0020,0x0030);
648 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
653 if( entry->GetValueCount() == 3 )
655 if (!entry->IsValueCountValid() )
657 gdcmErrorMacro( "Invalid Value Count" );
659 return (float)entry->GetValue(0);
665 * \brief gets the info from 0020,0032 : Image Position Patient
666 * else from 0020,0030 : Image Position (RET)
668 * @return up-left image corner Y position
670 float File::GetYOrigin()
672 DataEntry *entry = GetDataEntry(0x0020,0x0032);
675 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
676 entry = GetDataEntry(0x0020,0x0030);
679 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
684 if( entry->GetValueCount() == 3 )
686 if (!entry->IsValueCountValid() )
688 gdcmErrorMacro( "Invalid Value Count" );
690 return (float)entry->GetValue(1);
696 * \brief gets the info from 0020,0032 : Image Position Patient
697 * else from 0020,0030 : Image Position (RET)
698 * else from 0020,1041 : Slice Location
699 * else from 0020,0050 : Location
701 * @return up-left image corner Z position
703 float File::GetZOrigin()
705 DataEntry *entry = GetDataEntry(0x0020,0x0032);
708 if( entry->GetValueCount() == 3 )
710 if (!entry->IsValueCountValid() )
712 gdcmErrorMacro( "Invalid Value Count" );
714 return (float)entry->GetValue(2);
716 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
720 entry = GetDataEntry(0x0020,0x0030);
723 if( entry->GetValueCount() == 3 )
725 if (!entry->IsValueCountValid() )
727 gdcmErrorMacro( "Invalid Value Count" );
729 return (float)entry->GetValue(2);
731 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
735 // for *very* old ACR-NEMA images
736 entry = GetDataEntry(0x0020,0x1041);
739 if( entry->GetValueCount() == 1 )
741 if (!entry->IsValueCountValid() )
743 gdcmErrorMacro( "Invalid Value Count" );
745 return (float)entry->GetValue(0); // VM=1 !
747 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
751 entry = GetDataEntry(0x0020,0x0050);
754 if( entry->GetValueCount() == 1 )
756 if (!entry->IsValueCountValid() )
758 gdcmErrorMacro( "Invalid Value Count" );
760 return (float)entry->GetValue(0);
762 gdcmWarningMacro( "Wrong Location (0020,0050)");
765 return 0.; // Hopeless
769 * \brief gets the info from 0020,0037 : Image Orientation Patient
770 * or from 0020 0035 : Image Orientation (RET)
772 * (needed to organize DICOM files based on their x,y,z position)
774 * @param iop adress of the (6)float array to receive values.
775 * (defaulted as 1.,0.,0.,0.,1.,0. if nothing -or inconsistent stuff-
777 * @return true when one of the tag -with consistent values- is found
778 * false when nothing or inconsistent stuff - is found
780 bool File::GetImageOrientationPatient( float iop[6] )
782 std::string strImOriPat;
783 //iop is supposed to be float[6]
785 // 0020 0037 DS REL Image Orientation (Patient)
786 if ( (strImOriPat = GetEntryString(0x0020,0x0037)) != GDCM_UNFOUND )
788 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
789 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
791 iop[0] = iop[4] = 1.;
792 iop[1] = iop[2] = iop[3] = iop[5] = 0.;
793 gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037)."
794 << " Less than 6 values were found." );
801 // 0020 0035 DS REL Image Orientation (RET)
802 else if ( (strImOriPat = GetEntryString(0x0020,0x0035)) != GDCM_UNFOUND )
804 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
805 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
807 iop[0] = iop[4] = 1.;
808 iop[1] = iop[2] = iop[3] = iop[5] = 0.;
809 gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). "
810 << "Less than 6 values were found." );
820 * \brief Retrieve the number of Bits Stored (actually used)
821 * (as opposed to number of Bits Allocated)
822 * @return The encountered number of Bits Stored, 0 by default.
823 * 0 means the file is NOT USABLE. The caller has to check it !
825 int File::GetBitsStored()
827 DataEntry *entry = GetDataEntry(0x0028,0x0101);
830 gdcmWarningMacro("BitsStored (0028,0101) is supposed to be mandatory");
833 return (int)entry->GetValue(0);
837 * \brief Retrieve the number of Bits Allocated
838 * (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
839 * @return The encountered Number of Bits Allocated, 0 by default.
840 * 0 means the file is NOT USABLE. The caller has to check it !
842 int File::GetBitsAllocated()
844 DataEntry *entry = GetDataEntry(0x0028,0x0100);
847 gdcmWarningMacro("BitsAllocated (0028,0100) is supposed to be mandatory");
850 return (int)entry->GetValue(0);
854 * \brief Retrieve the high bit position.
855 * \warning The method defaults to 0 when information is missing.
856 * The responsability of checking this value is left to the caller.
857 * @return The high bit position when present. 0 when missing.
859 int File::GetHighBitPosition()
861 DataEntry *entry = GetDataEntry(0x0028,0x0102);
864 gdcmWarningMacro("HighBitPosition (0028,0102) is supposed to be mandatory");
867 return (int)entry->GetValue(0);
871 * \brief Retrieve the number of Samples Per Pixel
872 * (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
873 * @return The encountered number of Samples Per Pixel, 1 by default.
874 * (we assume Gray level Pixels)
876 int File::GetSamplesPerPixel()
878 DataEntry *entry = GetDataEntry(0x0028,0x0002);
881 gdcmWarningMacro("SamplesPerPixel (0028,0002) is supposed to be mandatory");
882 return 1; // Well, it's supposed to be mandatory ...
883 // but sometimes it's missing : *we* assume Gray pixels
885 return (int)entry->GetValue(0);
889 * \brief Retrieve the Planar Configuration for RGB images
890 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
891 * @return The encountered Planar Configuration, 0 by default.
893 int File::GetPlanarConfiguration()
895 DataEntry *entry = GetDataEntry(0x0028,0x0006);
900 return (int)entry->GetValue(0);
904 * \brief Return the size (in bytes) of a single pixel of data.
905 * @return The size in bytes of a single pixel of data; 0 by default
906 * 0 means the file is NOT USABLE; the caller will have to check
908 int File::GetPixelSize()
910 // 0028 0100 US IMG Bits Allocated
911 // (in order no to be messed up by old ACR-NEMA RGB images)
912 assert( !(GetEntryString(0x0028,0x0100) == "24") );
914 std::string pixelType = GetPixelType();
915 if ( pixelType == "8U" || pixelType == "8S" )
919 if ( pixelType == "16U" || pixelType == "16S")
923 if ( pixelType == "32U" || pixelType == "32S")
927 if ( pixelType == "FD" )
931 gdcmWarningMacro( "Unknown pixel type: " << pixelType);
936 * \brief Build the Pixel Type of the image.
937 * Possible values are:
938 * - 8U unsigned 8 bit,
940 * - 16U unsigned 16 bit,
941 * - 16S signed 16 bit,
942 * - 32U unsigned 32 bit,
943 * - 32S signed 32 bit,
944 * - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
945 * \warning 12 bit images appear as 16 bit.
946 * 24 bit images appear as 8 bit + photochromatic interp ="RGB "
947 * + Planar Configuration = 0
948 * @return 0S if nothing found. NOT USABLE file. The caller has to check
950 std::string File::GetPixelType()
952 std::string bitsAlloc = GetEntryString(0x0028, 0x0100); // Bits Allocated
953 if ( bitsAlloc == GDCM_UNFOUND )
955 gdcmWarningMacro( "Bits Allocated (0028,0100) supposed to be mandatory");
956 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
959 if ( bitsAlloc == "64" )
963 else if ( bitsAlloc == "12" )
965 // It will be unpacked
968 else if ( bitsAlloc == "24" )
970 // (in order no to be messed up by old RGB images)
975 if( IsSignedPixelData() )
983 return bitsAlloc + sign;
987 * \brief Check whether the pixels are signed (1) or UNsigned (0) data.
988 * \warning The method defaults to false (UNsigned) when tag 0028|0103
990 * The responsability of checking this value is left to the caller
991 * (NO transformation is performed on the pixels to make then >0)
992 * @return True when signed, false when UNsigned
994 bool File::IsSignedPixelData()
996 DataEntry *entry = GetDataEntry(0x0028, 0x0103);//"Pixel Representation"
999 gdcmWarningMacro( "Pixel Representation (0028,0103) supposed to be "
1003 return entry->GetValue(0) != 0;
1007 * \brief Check whether this a monochrome picture (gray levels) or not,
1008 * using "Photometric Interpretation" tag (0x0028,0x0004).
1009 * @return true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
1011 bool File::IsMonochrome()
1013 const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1014 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1015 || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1019 if ( PhotometricInterp == GDCM_UNFOUND )
1021 gdcmWarningMacro( "Photometric Interpretation (0028,0004) supposed to be "
1028 * \brief Check whether this a MONOCHROME1 picture (high values = dark)
1029 * or not using "Photometric Interpretation" tag (0x0028,0x0004).
1030 * @return true when "MONOCHROME1" . False otherwise.
1032 bool File::IsMonochrome1()
1034 const std::string &PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1035 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1039 if ( PhotometricInterp == GDCM_UNFOUND )
1041 gdcmWarningMacro( "Photometric Interpretation (0028,0004) : supposed to"
1042 << " be mandatory! ");
1048 * \brief Check whether this a "PALETTE COLOR" picture or not by accessing
1049 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1050 * @return true when "PALETTE COLOR". False otherwise.
1052 bool File::IsPaletteColor()
1054 std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1055 if ( PhotometricInterp == "PALETTE COLOR " )
1059 if ( PhotometricInterp == GDCM_UNFOUND )
1061 gdcmDebugMacro( "Not found : Palette color (0028,0004)");
1067 * \brief Check whether this a "YBR_FULL" color picture or not by accessing
1068 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1069 * @return true when "YBR_FULL". False otherwise.
1071 bool File::IsYBRFull()
1073 std::string PhotometricInterp = GetEntryString( 0x0028, 0x0004 );
1074 if ( PhotometricInterp == "YBR_FULL" )
1078 if ( PhotometricInterp == GDCM_UNFOUND )
1080 gdcmDebugMacro( "Not found : YBR Full (0028,0004)");
1086 * \brief tells us if LUT are used
1087 * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1088 * are NOT considered as LUT, since nobody knows
1089 * how to deal with them
1090 * Please warn me if you know sbdy that *does* know ... jprx
1091 * @return true if LUT Descriptors and LUT Tables were found
1095 // Check the presence of the LUT Descriptors, and LUT Tables
1097 if ( !GetDocEntry(0x0028,0x1101) )
1101 // LutDescriptorGreen
1102 if ( !GetDocEntry(0x0028,0x1102) )
1106 // LutDescriptorBlue
1107 if ( !GetDocEntry(0x0028,0x1103) )
1111 // Red Palette Color Lookup Table Data
1112 if ( !GetDocEntry(0x0028,0x1201) )
1116 // Green Palette Color Lookup Table Data
1117 if ( !GetDocEntry(0x0028,0x1202) )
1121 // Blue Palette Color Lookup Table Data
1122 if ( !GetDocEntry(0x0028,0x1203) )
1127 // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1128 // NOT taken into account, but we don't know how to use it ...
1133 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1135 * @return Lookup Table number of Bits , 0 by default
1136 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1137 * @ return bit number of each LUT item
1139 int File::GetLUTNbits()
1141 std::vector<std::string> tokens;
1144 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1145 // = Lookup Table Desc-Blue
1146 // Consistency already checked in GetLUTLength
1147 std::string lutDescription = GetEntryString(0x0028,0x1101);
1148 if ( lutDescription == GDCM_UNFOUND )
1153 tokens.clear(); // clean any previous value
1154 Util::Tokenize ( lutDescription, tokens, "\\" );
1155 //LutLength=atoi(tokens[0].c_str());
1156 //LutDepth=atoi(tokens[1].c_str());
1158 lutNbits = atoi( tokens[2].c_str() );
1165 *\brief gets the info from 0028,1052 : Rescale Intercept
1166 * @return Rescale Intercept. defaulted to 0.0 is not found or empty
1168 float File::GetRescaleIntercept()
1170 // 0028 1052 DS IMG Rescale Intercept
1171 DataEntry *entry = GetDataEntry(0x0028, 0x1052);
1174 gdcmWarningMacro( "Missing Rescale Intercept (0028,1052)");
1177 return (float)entry->GetValue(0);
1182 *\brief gets the info from 0028,1053 : Rescale Slope
1183 * @return Rescale Slope. defaulted to 0.0 is not found or empty
1185 float File::GetRescaleSlope()
1187 // 0028 1053 DS IMG Rescale Slope
1188 DataEntry *entry = GetDataEntry(0x0028, 0x1053);
1191 gdcmDebugMacro( "Missing Rescale Slope (0028,1053)");
1194 return (float)entry->GetValue(0);
1198 * \brief This function is intended to user who doesn't want
1199 * to have to manage a LUT and expects to get an RBG Pixel image
1200 * (or a monochrome one ...)
1201 * \warning to be used with GetImagePixels()
1202 * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1204 int File::GetNumberOfScalarComponents()
1206 if ( GetSamplesPerPixel() == 3 )
1211 // 0028 0100 US IMG Bits Allocated
1212 // (in order no to be messed up by old RGB images)
1213 if ( GetEntryString(0x0028,0x0100) == "24" )
1218 std::string strPhotometricInterpretation = GetEntryString(0x0028,0x0004);
1220 if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1222 if ( HasLUT() )// PALETTE COLOR is NOT enough
1232 // beware of trailing space at end of string
1233 // DICOM tags are never of odd length
1234 if ( strPhotometricInterpretation == GDCM_UNFOUND ||
1235 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1236 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1242 // we assume that *all* kinds of YBR are dealt with
1248 * \brief This function is intended to user that DOESN'T want
1249 * to get RGB pixels image when it's stored as a PALETTE COLOR image
1250 * - the (vtk) user is supposed to know how deal with LUTs -
1251 * \warning to be used with GetImagePixelsRaw()
1252 * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1254 int File::GetNumberOfScalarComponentsRaw()
1256 // 0028 0100 US IMG Bits Allocated
1257 // (in order no to be messed up by old RGB images)
1258 if ( File::GetEntryString(0x0028,0x0100) == "24" )
1263 // we assume that *all* kinds of YBR are dealt with
1264 return GetSamplesPerPixel();
1268 * \brief Recover the offset (from the beginning of the file)
1269 * of *image* pixels (not *icone image* pixels, if any !)
1270 * @return Pixel Offset
1272 size_t File::GetPixelOffset()
1274 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1277 return pxlElement->GetOffset();
1281 gdcmWarningMacro( "Big trouble : Pixel Element ("
1282 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1288 * \brief Recover the pixel area length (in Bytes)
1289 * @return Pixel Element Length, as stored in the header
1290 * (NOT the memory space necessary to hold the Pixels
1291 * -in case of embeded compressed image-)
1292 * 0 : NOT USABLE file. The caller has to check.
1294 size_t File::GetPixelAreaLength()
1296 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1299 return pxlElement->GetLength();
1303 gdcmWarningMacro( "Big trouble : Pixel Element ("
1304 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1310 * \brief Adds the characteristics of a new element we want to anonymize
1311 * @param group Group number of the target tag.
1312 * @param elem Element number of the target tag.
1313 * @param value new value (string) to substitute with
1315 void File::AddAnonymizeElement (uint16_t group, uint16_t elem,
1316 std::string const &value)
1322 UserAnonymizeList.push_back(el);
1326 * \brief Overwrites in the file the values of the DicomElements
1329 void File::AnonymizeNoLoad()
1331 std::fstream *fp = new std::fstream(Filename.c_str(),
1332 std::ios::in | std::ios::out | std::ios::binary);
1336 uint32_t valLgth = 0;
1337 std::string *spaces;
1338 for (ListElements::iterator it = UserAnonymizeList.begin();
1339 it != UserAnonymizeList.end();
1342 d = GetDocEntry( (*it).Group, (*it).Elem);
1347 if ( dynamic_cast<SeqEntry *>(d) )
1349 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1353 offset = d->GetOffset();
1354 lgth = d->GetLength();
1357 spaces = new std::string( lgth-valLgth, ' ');
1358 (*it).Value = (*it).Value + *spaces;
1361 fp->seekp( offset, std::ios::beg );
1362 fp->write( (*it).Value.c_str(), lgth );
1370 * \brief anonymize a File (remove Patient's personal info passed with
1371 * AddAnonymizeElement()
1372 * \note You cannot Anonymize a DataEntry (to be fixed)
1374 bool File::AnonymizeFile()
1376 // If Anonymisation list is empty, let's perform some basic anonymization
1377 if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1379 // If exist, replace by spaces
1380 SetEntryString(" ",0x0010, 0x2154); // Telephone
1381 SetEntryString(" ",0x0010, 0x1040); // Adress
1382 SetEntryString(" ",0x0010, 0x0020); // Patient ID
1384 DocEntry *patientNameHE = GetDocEntry (0x0010, 0x0010);
1386 if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1388 std::string studyInstanceUID = GetEntryString (0x0020, 0x000d);
1389 if ( studyInstanceUID != GDCM_UNFOUND )
1391 SetEntryString(studyInstanceUID, 0x0010, 0x0010);
1395 SetEntryString("anonymized", 0x0010, 0x0010);
1402 for (ListElements::iterator it = UserAnonymizeList.begin();
1403 it != UserAnonymizeList.end();
1406 d = GetDocEntry( (*it).Group, (*it).Elem);
1411 if ( dynamic_cast<SeqEntry *>(d) )
1413 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1417 if ( dynamic_cast<DataEntry *>(d) )
1419 gdcmWarningMacro( "To 'Anonymize' a DataEntry, better use AnonymizeNoLoad (FIXME) ");
1423 SetEntryString ((*it).Value, (*it).Group, (*it).Elem);
1427 // In order to make definitively impossible any further identification
1428 // remove or replace all the stuff that contains a Date
1430 //0008 0012 DA ID Instance Creation Date
1431 //0008 0020 DA ID Study Date
1432 //0008 0021 DA ID Series Date
1433 //0008 0022 DA ID Acquisition Date
1434 //0008 0023 DA ID Content Date
1435 //0008 0024 DA ID Overlay Date
1436 //0008 0025 DA ID Curve Date
1437 //0008 002a DT ID Acquisition Datetime
1438 //0018 9074 DT ACQ Frame Acquisition Datetime
1439 //0018 9151 DT ACQ Frame Reference Datetime
1440 //0018 a002 DT ACQ Contribution Date Time
1441 //0020 3403 SH REL Modified Image Date (RET)
1442 //0032 0032 DA SDY Study Verified Date
1443 //0032 0034 DA SDY Study Read Date
1444 //0032 1000 DA SDY Scheduled Study Start Date
1445 //0032 1010 DA SDY Scheduled Study Stop Date
1446 //0032 1040 DA SDY Study Arrival Date
1447 //0032 1050 DA SDY Study Completion Date
1448 //0038 001a DA VIS Scheduled Admission Date
1449 //0038 001c DA VIS Scheduled Discharge Date
1450 //0038 0020 DA VIS Admitting Date
1451 //0038 0030 DA VIS Discharge Date
1452 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1453 //0040 0004 DA PRC Scheduled Procedure Step End Date
1454 //0040 0244 DA PRC Performed Procedure Step Start Date
1455 //0040 0250 DA PRC Performed Procedure Step End Date
1456 //0040 2004 DA PRC Issue Date of Imaging Service Request
1457 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1458 //0040 4011 DT PRC Expected Completion Date and Time
1459 //0040 a030 DT PRC Verification Date Time
1460 //0040 a032 DT PRC Observation Date Time
1461 //0040 a120 DT PRC DateTime
1462 //0040 a121 DA PRC Date
1463 //0040 a13a DT PRC Referenced Datetime
1464 //0070 0082 DA ??? Presentation Creation Date
1465 //0100 0420 DT ??? SOP Autorization Date and Time
1466 //0400 0105 DT ??? Digital Signature DateTime
1467 //2100 0040 DA PJ Creation Date
1468 //3006 0008 DA SSET Structure Set Date
1469 //3008 0024 DA ??? Treatment Control Point Date
1470 //3008 0054 DA ??? First Treatment Date
1471 //3008 0056 DA ??? Most Recent Treatment Date
1472 //3008 0162 DA ??? Safe Position Exit Date
1473 //3008 0166 DA ??? Safe Position Return Date
1474 //3008 0250 DA ??? Treatment Date
1475 //300a 0006 DA RT RT Plan Date
1476 //300a 022c DA RT Air Kerma Rate Reference Date
1477 //300e 0004 DA RT Review Date
1483 * \brief Performs some consistency checking on various 'File related'
1484 * (as opposed to 'DicomDir related') entries
1485 * then writes in a file all the (Dicom Elements) included the Pixels
1486 * @param fileName file name to write to
1487 * @param writetype type of the file to be written
1488 * (ACR, ExplicitVR, ImplicitVR)
1490 bool File::Write(std::string fileName, FileType writetype)
1492 std::ofstream *fp = new std::ofstream(fileName.c_str(),
1493 std::ios::out | std::ios::binary);
1496 gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1500 // Entry : 0002|0000 = group length -> recalculated
1501 DataEntry *e0000 = GetDataEntry(0x0002,0x0000);
1504 std::ostringstream sLen;
1505 sLen << ComputeGroup0002Length( );
1506 e0000->SetString(sLen.str());
1509 // FIXME : Derma?.dcm does not have it...let's remove it ?!? JPRx
1510 if( writetype != JPEG )
1512 int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1515 // no (GrPixel, NumPixel) element
1516 std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1517 s_lgPix = Util::DicomString( s_lgPix.c_str() );
1518 InsertEntryString(s_lgPix,GrPixel, 0x0000);
1521 Document::WriteContent(fp, writetype);
1529 //-----------------------------------------------------------------------------
1533 //-----------------------------------------------------------------------------
1536 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1537 * Compute the RLE extra information and store it in \ref RLEInfo
1538 * for later pixel retrieval usage.
1540 void File::ComputeRLEInfo()
1542 std::string ts = GetTransferSyntax();
1543 if ( !Global::GetTS()->IsRLELossless(ts) )
1548 // Encoded pixel data: for the time being we are only concerned with
1549 // Jpeg or RLE Pixel data encodings.
1550 // As stated in PS 3.5-2003, section 8.2 p44:
1551 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1552 // value representation OB is used".
1553 // Hence we expect an OB value representation. Concerning OB VR,
1554 // the section PS 3.5-2003, section A.4.c p 58-59, states:
1555 // "For the Value Representations OB and OW, the encoding shall meet the
1556 // following specifications depending on the Data element tag:"
1558 // - the first item in the sequence of items before the encoded pixel
1559 // data stream shall be basic offset table item. The basic offset table
1560 // item value, however, is not required to be present"
1561 ReadEncapsulatedBasicOffsetTable();
1563 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1564 // Loop on the individual frame[s] and store the information
1565 // on the RLE fragments in a RLEFramesInfo.
1566 // Note: - when only a single frame is present, this is a
1568 // - when more than one frame are present, then we are in
1569 // the case of a multi-frame image.
1573 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1575 // Since we have read the basic offset table, let's check the value were correct
1576 // or else produce a warning:
1577 if ( BasicOffsetTableItemValue )
1579 // If a BasicOffsetTableItemValue was read
1580 uint32_t individualLength = BasicOffsetTableItemValue[i];
1581 assert( individualLength == sum ); // REMOVE that if this is a problem
1582 if( individualLength != sum )
1584 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght" );
1586 sum += frameLength + 8;
1589 // Parse the RLE Header and store the corresponding RLE Segment
1590 // Offset Table information on fragments of this current Frame.
1591 // Note that the fragment pixels themselves are not loaded
1592 // (but just skipped).
1593 long frameOffset = Fp->tellg();
1595 uint32_t nbRleSegments = ReadInt32();
1596 if ( nbRleSegments > 16 )
1598 // There should be at most 15 segments (refer to RLEFrame class)
1599 gdcmWarningMacro( "Too many segments.");
1602 uint32_t rleSegmentOffsetTable[16];
1603 for( int k = 1; k <= 15; k++ )
1605 rleSegmentOffsetTable[k] = ReadInt32();
1608 // Deduce from both RLE Header and frameLength
1609 // the fragment length, and again store this info
1610 // in a RLEFramesInfo.
1611 long rleSegmentLength[15];
1612 // skipping (not reading) RLE Segments
1613 if ( nbRleSegments > 1)
1615 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1617 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
1618 - rleSegmentOffsetTable[k];
1619 SkipBytes(rleSegmentLength[k]);
1623 rleSegmentLength[nbRleSegments] = frameLength
1624 - rleSegmentOffsetTable[nbRleSegments];
1625 SkipBytes(rleSegmentLength[nbRleSegments]);
1627 // Store the collected info
1628 RLEFrame *newFrame = new RLEFrame;
1629 newFrame->SetNumberOfFragments(nbRleSegments);
1630 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1632 newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1633 newFrame->SetLength(uk,rleSegmentLength[uk]);
1635 RLEInfo->AddFrame(newFrame);
1638 // Make sure that we encounter a 'Sequence Delimiter Item'
1639 // at the end of the item :
1640 if ( !ReadTag(0xfffe, 0xe0dd) )
1642 gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1647 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1648 * Compute the jpeg extra information (fragment[s] offset[s] and
1649 * length) and store it[them] in \ref JPEGInfo for later pixel
1652 void File::ComputeJPEGFragmentInfo()
1654 // If you need to, look for comments of ComputeRLEInfo().
1655 std::string ts = GetTransferSyntax();
1656 if ( ! Global::GetTS()->IsJPEG(ts) )
1661 ReadEncapsulatedBasicOffsetTable();
1663 // Loop on the fragments[s] and store the parsed information in a
1665 long fragmentLength;
1668 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1670 // Since we have read the basic offset table, let's check the value were correct
1671 // or else produce a warning:
1672 // A.4 Transfer syntaxes for encapsulation of encoded pixel data:
1673 // When the Item Value is present, the Basic Offset Table Item Value shall contain
1674 // concatenated 32-bit unsigned integer values that are byte offsets to the first
1675 // byte of the Item Tag of the first fragment for each frame in the Sequence of
1676 // Items. These offsets are measured from the first byte of the first Item Tag
1677 // following the Basic Offset Table item (See Table A.4-2).
1679 if ( BasicOffsetTableItemValue )
1681 // If a BasicOffsetTableItemValue was read
1682 uint32_t individualLength = BasicOffsetTableItemValue[i];
1683 //assert( individualLength == sum ); // Seems like 00191113.dcm is off by one ??
1684 if( individualLength != sum )
1686 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght:" <<
1687 individualLength << " != " << sum );
1689 sum += fragmentLength + 8;
1693 long fragmentOffset = Fp->tellg();
1694 // Store the collected info
1695 JPEGFragment *newFragment = new JPEGFragment;
1696 newFragment->SetOffset(fragmentOffset);
1697 newFragment->SetLength(fragmentLength);
1698 JPEGInfo->AddFragment(newFragment);
1700 SkipBytes(fragmentLength);
1703 // Make sure that we encounter a 'Sequence Delimiter Item'
1704 // at the end of the item :
1705 if ( !ReadTag(0xfffe, 0xe0dd) )
1707 gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1712 * \brief Assuming the internal file pointer \ref Document::Fp
1713 * is placed at the beginning of a tag, check whether this
1714 * tag is (TestGroup, TestElem).
1715 * \warning On success the internal file pointer \ref Document::Fp
1716 * is modified to point after the tag.
1717 * On failure (i.e. when the tag wasn't the expected tag
1718 * (TestGroup, TestElem) the internal file pointer
1719 * \ref Document::Fp is restored to it's original position.
1720 * @param testGroup The expected group of the tag.
1721 * @param testElem The expected Element of the tag.
1722 * @return True on success, false otherwise.
1724 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1726 long positionOnEntry = Fp->tellg();
1727 long currentPosition = Fp->tellg(); // On debugging purposes
1729 // Read the Item Tag group and element, and make
1730 // sure they are what we expected:
1731 uint16_t itemTagGroup;
1732 uint16_t itemTagElem;
1735 itemTagGroup = ReadInt16();
1736 itemTagElem = ReadInt16();
1738 catch ( FormatError )
1740 gdcmErrorMacro( "Can not read tag for "
1741 << " We should have found tag ("
1742 << DictEntry::TranslateToKey(testGroup,testElem) << ")"
1747 if ( itemTagGroup != testGroup || itemTagElem != testElem )
1749 // in order not to pollute output we don't warn on 'delimitors'
1750 if (itemTagGroup != 0xfffe || testGroup != 0xfffe )
1751 gdcmWarningMacro( "Wrong Item Tag found:"
1752 << " We should have found tag ("
1753 << DictEntry::TranslateToKey(testGroup,testElem) << ")" << std::endl
1754 << " but instead we encountered tag ("
1755 << DictEntry::TranslateToKey(itemTagGroup,itemTagElem) << ")"
1756 << " at address: " << " 0x(" << std::hex
1757 << (unsigned int)currentPosition << std::dec << ")"
1759 Fp->seekg(positionOnEntry, std::ios::beg);
1767 * \brief Assuming the internal file pointer \ref Document::Fp
1768 * is placed at the beginning of a tag (TestGroup, TestElement),
1769 * read the length associated to the Tag.
1770 * \warning On success the internal file pointer \ref Document::Fp
1771 * is modified to point after the tag and it's length.
1772 * On failure (i.e. when the tag wasn't the expected tag
1773 * (TestGroup, TestElement) the internal file pointer
1774 * \ref Document::Fp is restored to it's original position.
1775 * @param testGroup The expected Group of the tag.
1776 * @param testElem The expected Element of the tag.
1777 * @return On success returns the length associated to the tag. On failure
1780 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1783 if ( !ReadTag(testGroup, testElem) )
1785 // Avoid polutting output
1786 if ( testGroup != 0xfffe )
1787 gdcmErrorMacro( "ReadTag did not succeed for ("
1788 << DictEntry::TranslateToKey(testGroup,testElem)
1793 //// Then read the associated Item Length
1794 long currentPosition = Fp->tellg();
1795 uint32_t itemLength = ReadInt32();
1796 gdcmDebugMacro( "Basic Item Length is: " << itemLength
1797 << " at address: " << std::hex << (unsigned int)currentPosition);
1802 * \brief When parsing the Pixel Data of an encapsulated file, read
1803 * the basic offset table (when present, and BTW dump it).
1805 void File::ReadEncapsulatedBasicOffsetTable()
1807 //// Read the Basic Offset Table Item Tag length...
1808 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1810 // When present, read the basic offset table itself.
1811 // Notes: - since the presence of this basic offset table is optional
1812 // we can't rely on it for the implementation, and we will simply
1813 // trash it's content (when present).
1814 // - still, when present, we could add some further checks on the
1815 // lengths, but we won't bother with such fuses for the time being.
1816 if ( itemLength != 0 )
1818 char *charBasicOffsetTableItemValue = new char[itemLength];
1819 Fp->read(charBasicOffsetTableItemValue, itemLength);
1820 unsigned int nbEntries = itemLength/4;
1821 assert( nbEntries*4 == itemLength); // Make sure this is a multiple
1822 BasicOffsetTableItemValue = new uint32_t[nbEntries];
1824 for (unsigned int i=0; i < nbEntries; i++ )
1826 BasicOffsetTableItemValue[i] = *((uint32_t*)(&charBasicOffsetTableItemValue[4*i]));
1827 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1828 uint32_t val = BasicOffsetTableItemValue[i];
1829 BasicOffsetTableItemValue[i]
1830 = ( (val<<24) | ((val<<8) & 0x00ff0000) |
1831 ( (val>>8) & 0x0000ff00) | (val>>24) );
1833 gdcmDebugMacro( "Read one length for: " <<
1834 std::hex << BasicOffsetTableItemValue[i] );
1837 delete[] charBasicOffsetTableItemValue;
1841 // These are the deprecated method that one day should be removed (after the next release)
1843 //#ifndef GDCM_LEGACY_REMOVE
1845 * \ brief Loader. (DEPRECATED : temporaryly kept not to break the API)
1846 * @ param fileName file to be open for parsing
1847 * @ return false if file cannot be open or no swap info was found,
1848 * or no tag was found.
1849 * @ deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
1852 bool File::Load( std::string const &fileName )
1854 GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
1856 SetFileName( fileName );
1857 if ( ! this->Document::Load( ) )
1860 return DoTheLoadingJob( );
1865 //-----------------------------------------------------------------------------
1868 //-----------------------------------------------------------------------------
1869 } // end namespace gdcm