1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2005/09/21 17:16:15 $
7 Version: $Revision: 1.271 $
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 What is it used for?
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
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 "gdcmValEntry.h"
96 #include "gdcmBinEntry.h"
97 #include "gdcmSeqEntry.h"
98 #include "gdcmRLEFramesInfo.h"
99 #include "gdcmJPEGFragmentsInfo.h"
102 #include <stdio.h> //sscanf
103 #include <stdlib.h> // for atoi
108 //-----------------------------------------------------------------------------
109 // Constructor / Destructor
112 * \brief Constructor used when we want to generate dicom files from scratch
117 RLEInfo = new RLEFramesInfo;
118 JPEGInfo = new JPEGFragmentsInfo;
119 GrPixel = 0x7fe0; // to avoid further troubles
125 * \brief Canonical destructor.
135 //-----------------------------------------------------------------------------
139 * @return false if file cannot be open or no swap info was found,
140 * or no tag was found.
144 if ( ! this->Document::Load( ) )
147 return DoTheLoadingJob( );
151 * \brief Does the Loading Job (internal use only)
152 * @return false if file cannot be open or no swap info was found,
153 * or no tag was found.
155 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 = GetEntryValue(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 BinEntry to change the DictEntry
215 // The changed DictEntry will have
216 // - a correct PixelVR OB or OW)
217 // - the name to "Pixel Data"
218 BinEntry *oldEntry = dynamic_cast<BinEntry *>(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 = NewVirtualDictEntry(GrPixel,NumPixel,
233 PixelVR,"1","Pixel Data");
235 BinEntry *newEntry = new BinEntry(newDict);
236 newEntry->Copy(entry);
237 newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
238 oldEntry->SetSelfArea(false);
240 RemoveEntry(oldEntry);
248 * \brief This predicate, based on hopefully reasonable heuristics,
249 * decides whether or not the current File was properly parsed
250 * and contains the mandatory information for being considered as
251 * a well formed and usable Dicom/Acr File.
252 * @return true when File is the one of a reasonable Dicom/Acr file,
255 bool File::IsReadable()
257 if ( !Document::IsReadable() )
262 const std::string &res = GetEntryValue(0x0028, 0x0005);
263 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
265 gdcmWarningMacro("Wrong Image Dimensions" << res);
266 return false; // Image Dimensions
268 bool b0028_0100 = true;
269 if ( !GetDocEntry(0x0028, 0x0100) )
271 gdcmWarningMacro("Bits Allocated (0028|0100) not found");
272 //return false; // "Bits Allocated"
275 bool b0028_0101 = true;
276 if ( !GetDocEntry(0x0028, 0x0101) )
278 gdcmWarningMacro("Bits Stored (0028|0101) not found");
279 //return false; // "Bits Stored"
282 bool b0028_0102 = true;
283 if ( !GetDocEntry(0x0028, 0x0102) )
285 gdcmWarningMacro("Hight Bit (0028|0102) not found");
286 //return false; // "High Bit"
289 bool b0028_0103 = true;
290 if ( !GetDocEntry(0x0028, 0x0103) )
292 gdcmWarningMacro("Pixel Representation (0028|0103) not found");
293 //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
297 if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
299 gdcmWarningMacro("Too much mandatory Tags missing !");
303 if ( !GetDocEntry(GrPixel, NumPixel) )
305 gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
306 GrPixel << "|" << NumPixel << "not found");
307 return false; // Pixel Dicom Element not found :-(
313 * \brief gets the info from 0020,0013 : Image Number else 0.
314 * @return image number
316 int File::GetImageNumber()
318 //0020 0013 : Image Number
319 std::string strImNumber = GetEntryValue(0x0020,0x0013);
320 if ( strImNumber != GDCM_UNFOUND )
322 return atoi( strImNumber.c_str() );
328 * \brief gets the info from 0008,0060 : Modality
329 * @return Modality Type
331 ModalityType File::GetModality()
333 // 0008 0060 : Modality
334 std::string strModality = GetEntryValue(0x0008,0x0060);
335 if ( strModality != GDCM_UNFOUND )
337 if ( strModality.find("AU") < strModality.length()) return AU;
338 else if ( strModality.find("AS") < strModality.length()) return AS;
339 else if ( strModality.find("BI") < strModality.length()) return BI;
340 else if ( strModality.find("CF") < strModality.length()) return CF;
341 else if ( strModality.find("CP") < strModality.length()) return CP;
342 else if ( strModality.find("CR") < strModality.length()) return CR;
343 else if ( strModality.find("CT") < strModality.length()) return CT;
344 else if ( strModality.find("CS") < strModality.length()) return CS;
345 else if ( strModality.find("DD") < strModality.length()) return DD;
346 else if ( strModality.find("DF") < strModality.length()) return DF;
347 else if ( strModality.find("DG") < strModality.length()) return DG;
348 else if ( strModality.find("DM") < strModality.length()) return DM;
349 else if ( strModality.find("DS") < strModality.length()) return DS;
350 else if ( strModality.find("DX") < strModality.length()) return DX;
351 else if ( strModality.find("ECG") < strModality.length()) return ECG;
352 else if ( strModality.find("EPS") < strModality.length()) return EPS;
353 else if ( strModality.find("FA") < strModality.length()) return FA;
354 else if ( strModality.find("FS") < strModality.length()) return FS;
355 else if ( strModality.find("HC") < strModality.length()) return HC;
356 else if ( strModality.find("HD") < strModality.length()) return HD;
357 else if ( strModality.find("LP") < strModality.length()) return LP;
358 else if ( strModality.find("LS") < strModality.length()) return LS;
359 else if ( strModality.find("MA") < strModality.length()) return MA;
360 else if ( strModality.find("MR") < strModality.length()) return MR;
361 else if ( strModality.find("NM") < strModality.length()) return NM;
362 else if ( strModality.find("OT") < strModality.length()) return OT;
363 else if ( strModality.find("PT") < strModality.length()) return PT;
364 else if ( strModality.find("RF") < strModality.length()) return RF;
365 else if ( strModality.find("RG") < strModality.length()) return RG;
366 else if ( strModality.find("RTDOSE")
367 < strModality.length()) return RTDOSE;
368 else if ( strModality.find("RTIMAGE")
369 < strModality.length()) return RTIMAGE;
370 else if ( strModality.find("RTPLAN")
371 < strModality.length()) return RTPLAN;
372 else if ( strModality.find("RTSTRUCT")
373 < strModality.length()) return RTSTRUCT;
374 else if ( strModality.find("SM") < strModality.length()) return SM;
375 else if ( strModality.find("ST") < strModality.length()) return ST;
376 else if ( strModality.find("TG") < strModality.length()) return TG;
377 else if ( strModality.find("US") < strModality.length()) return US;
378 else if ( strModality.find("VF") < strModality.length()) return VF;
379 else if ( strModality.find("XA") < strModality.length()) return XA;
380 else if ( strModality.find("XC") < strModality.length()) return XC;
384 /// \todo throw error return value ???
385 /// specified <> unknown in our database
393 * \brief Retrieve the number of columns of image.
394 * @return The encountered size when found, 0 by default.
395 * 0 means the file is NOT USABLE. The caller will have to check
399 const std::string &strSize = GetEntryValue(0x0028,0x0011);
400 if ( strSize == GDCM_UNFOUND )
404 return atoi( strSize.c_str() );
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 const std::string &strSize = GetEntryValue(0x0028,0x0010);
416 if ( strSize != GDCM_UNFOUND )
418 return atoi( strSize.c_str() );
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 const std::string &strSize = GetEntryValue(0x0028,0x0008);
444 if ( strSize != GDCM_UNFOUND )
446 return atoi( strSize.c_str() );
449 // We then consider the "Planes" entry as the third dimension
450 const std::string &strSize2 = GetEntryValue(0x0028,0x0012);
451 if ( strSize2 != GDCM_UNFOUND )
453 return atoi( strSize2.c_str() );
459 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
460 * then 0028,0030 : Pixel Spacing
462 * @return X dimension of a pixel
464 float File::GetXSpacing()
466 float xspacing = 1.0;
467 float yspacing = 1.0;
470 // To follow David Clunie's advice, we first check ImagerPixelSpacing
472 const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
473 if ( strImagerPixelSpacing != GDCM_UNFOUND )
475 if ( ( nbValues = sscanf( strImagerPixelSpacing.c_str(),
476 "%f\\%f", &yspacing, &xspacing)) != 2 )
478 // if no values, xspacing is set to 1.0
481 // if single value is found, xspacing is defaulted to yspacing
485 if ( xspacing == 0.0 )
492 const std::string &strSpacing = GetEntryValue(0x0028,0x0030);
494 if ( strSpacing == GDCM_UNFOUND )
496 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
500 if ( ( nbValues = sscanf( strSpacing.c_str(),
501 "%f \\%f ", &yspacing, &xspacing)) != 2 )
503 // if no values, xspacing is set to 1.0
506 // if single value is found, xspacing is defaulted to yspacing
510 if ( xspacing == 0.0 )
516 // to avoid troubles with David Clunie's-like images (at least one)
517 if ( xspacing == 0. && yspacing == 0.)
522 gdcmWarningMacro("gdcmData/CT-MONO2-8-abdo.dcm-like problem");
523 // seems to be a bug in the header ...
524 nbValues = sscanf( strSpacing.c_str(), "%f \\0\\%f ", &yspacing, &xspacing);
525 gdcmAssertMacro( nbValues == 2 );
532 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
533 * then from 0028,0030 : Pixel Spacing
535 * @return Y dimension of a pixel
537 float File::GetYSpacing()
541 // To follow David Clunie's advice, we first check ImagerPixelSpacing
543 const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
544 if ( strImagerPixelSpacing != GDCM_UNFOUND )
546 nbValues = sscanf( strImagerPixelSpacing.c_str(), "%f", &yspacing);
548 // if sscanf cannot read any float value, it won't affect yspacing
552 if ( yspacing == 0.0 )
558 std::string strSpacing = GetEntryValue(0x0028,0x0030);
559 if ( strSpacing == GDCM_UNFOUND )
561 gdcmWarningMacro("Unfound Pixel Spacing (0028,0030)");
565 // if sscanf cannot read any float value, it won't affect yspacing
566 nbValues = sscanf( strSpacing.c_str(), "%f", &yspacing);
568 // if no values, yspacing is set to 1.0
572 if ( yspacing == 0.0 )
579 * \brief gets the info from 0018,0088 : Space Between Slices
580 * else from 0018,0050 : Slice Thickness
582 * @return Z dimension of a voxel-to be
584 float File::GetZSpacing()
586 // Spacing Between Slices : distance between the middle of 2 slices
588 // jointives (Spacing between Slices = Slice Thickness)
589 // overlapping (Spacing between Slices < Slice Thickness)
590 // disjointes (Spacing between Slices > Slice Thickness)
591 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
592 // It only concerns the MRI guys, not people wanting to visualize volumes
593 // If Spacing Between Slices is missing,
594 // we suppose slices joint together
596 const std::string &strSpacingBSlices = GetEntryValue(0x0018,0x0088);
598 if ( strSpacingBSlices == GDCM_UNFOUND )
600 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
601 const std::string &strSliceThickness = GetEntryValue(0x0018,0x0050);
602 if ( strSliceThickness == GDCM_UNFOUND )
604 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
609 // if no 'Spacing Between Slices' is found,
610 // we assume slices join together
611 // (no overlapping, no interslice gap)
612 // if they don't, we're fucked up
613 return (float)atof( strSliceThickness.c_str() );
617 return (float)atof( strSpacingBSlices.c_str() );
621 * \brief gets the info from 0020,0032 : Image Position Patient
622 * else from 0020,0030 : Image Position (RET)
624 * @return up-left image corner X position
626 float File::GetXOrigin()
628 float xImPos, yImPos, zImPos;
629 std::string strImPos = GetEntryValue(0x0020,0x0032);
631 if ( strImPos == GDCM_UNFOUND )
633 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
634 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
635 if ( strImPos == GDCM_UNFOUND )
637 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
642 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
651 * \brief gets the info from 0020,0032 : Image Position Patient
652 * else from 0020,0030 : Image Position (RET)
654 * @return up-left image corner Y position
656 float File::GetYOrigin()
658 float xImPos, yImPos, zImPos;
659 std::string strImPos = GetEntryValue(0x0020,0x0032);
661 if ( strImPos == GDCM_UNFOUND)
663 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
664 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
665 if ( strImPos == GDCM_UNFOUND )
667 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
672 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
681 * \brief gets the info from 0020,0032 : Image Position Patient
682 * else from 0020,0030 : Image Position (RET)
683 * else from 0020,1041 : Slice Location
684 * else from 0020,0050 : Location
686 * @return up-left image corner Z position
688 float File::GetZOrigin()
690 float xImPos, yImPos, zImPos;
691 std::string strImPos = GetEntryValue(0x0020,0x0032);
693 if ( strImPos != GDCM_UNFOUND )
695 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3)
697 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
698 return 0.; // bug in the element 0x0020,0x0032
706 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
707 if ( strImPos != GDCM_UNFOUND )
709 if ( sscanf( strImPos.c_str(),
710 "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos ) != 3 )
712 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
713 return 0.; // bug in the element 0x0020,0x0032
721 // for *very* old ACR-NEMA images
722 std::string strSliceLocation = GetEntryValue(0x0020,0x1041);
723 if ( strSliceLocation != GDCM_UNFOUND )
725 if ( sscanf( strSliceLocation.c_str(), "%f ", &zImPos) != 1)
727 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
728 return 0.; // bug in the element 0x0020,0x1041
735 gdcmWarningMacro( "Unfound Slice Location (0020,1041)");
737 std::string strLocation = GetEntryValue(0x0020,0x0050);
738 if ( strLocation != GDCM_UNFOUND )
740 if ( sscanf( strLocation.c_str(), "%f ", &zImPos) != 1 )
742 gdcmWarningMacro( "Wrong Location (0020,0050)");
743 return 0.; // bug in the element 0x0020,0x0050
750 gdcmWarningMacro( "Unfound Location (0020,0050)");
752 return 0.; // Hopeless
756 * \brief gets the info from 0020,0037 : Image Orientation Patient
757 * or from 0020 0035 : Image Orientation (RET)
758 * (needed to organize DICOM files based on their x,y,z position)
759 * @param iop adress of the (6)float array to receive values
760 * @return true when one of the tag is found
761 * false when nothing is found
763 bool File::GetImageOrientationPatient( float iop[6] )
765 std::string strImOriPat;
766 //iop is supposed to be float[6]
767 iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
769 // 0020 0037 DS REL Image Orientation (Patient)
770 if ( (strImOriPat = GetEntryValue(0x0020,0x0037)) != GDCM_UNFOUND )
772 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
773 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
775 gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037)."
776 << " Less than 6 values were found." );
781 // 0020 0035 DS REL Image Orientation (RET)
782 else if ( (strImOriPat = GetEntryValue(0x0020,0x0035)) != GDCM_UNFOUND )
784 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
785 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
787 gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). "
788 << "Less than 6 values were found." );
798 * \brief Retrieve the number of Bits Stored (actually used)
799 * (as opposed to number of Bits Allocated)
800 * @return The encountered number of Bits Stored, 0 by default.
801 * 0 means the file is NOT USABLE. The caller has to check it !
803 int File::GetBitsStored()
805 std::string strSize = GetEntryValue( 0x0028, 0x0101 );
806 if ( strSize == GDCM_UNFOUND )
808 gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
809 return 0; // It's supposed to be mandatory
810 // the caller will have to check
812 return atoi( strSize.c_str() );
816 * \brief Retrieve the number of Bits Allocated
817 * (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
818 * @return The encountered Number of Bits Allocated, 0 by default.
819 * 0 means the file is NOT USABLE. The caller has to check it !
821 int File::GetBitsAllocated()
823 std::string strSize = GetEntryValue(0x0028,0x0100);
824 if ( strSize == GDCM_UNFOUND )
826 gdcmWarningMacro( "(0028,0100) is supposed to be mandatory");
827 return 0; // It's supposed to be mandatory
828 // the caller will have to check
830 return atoi( strSize.c_str() );
834 * \brief Retrieve the high bit position.
835 * \warning The method defaults to 0 when information is missing.
836 * The responsability of checking this value is left to the caller.
837 * @return The high bit position when present. 0 when missing.
839 int File::GetHighBitPosition()
841 std::string strSize = GetEntryValue( 0x0028, 0x0102 );
842 if ( strSize == GDCM_UNFOUND )
844 gdcmWarningMacro( "(0028,0102) is supposed to be mandatory");
847 return atoi( strSize.c_str() );
851 * \brief Retrieve the number of Samples Per Pixel
852 * (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
853 * @return The encountered number of Samples Per Pixel, 1 by default.
854 * (we assume Gray level Pixels)
856 int File::GetSamplesPerPixel()
858 const std::string &strSize = GetEntryValue(0x0028,0x0002);
859 if ( strSize == GDCM_UNFOUND )
861 gdcmWarningMacro( "(0028,0002) is supposed to be mandatory");
862 return 1; // Well, it's supposed to be mandatory ...
863 // but sometimes it's missing : *we* assume Gray pixels
865 return atoi( strSize.c_str() );
869 * \brief Retrieve the Planar Configuration for RGB images
870 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
871 * @return The encountered Planar Configuration, 0 by default.
873 int File::GetPlanarConfiguration()
875 std::string strSize = GetEntryValue(0x0028,0x0006);
876 if ( strSize == GDCM_UNFOUND )
878 gdcmWarningMacro( "Not found : Planar Configuration (0028,0006)");
881 return atoi( strSize.c_str() );
885 * \brief Return the size (in bytes) of a single pixel of data.
886 * @return The size in bytes of a single pixel of data; 0 by default
887 * 0 means the file is NOT USABLE; the caller will have to check
889 int File::GetPixelSize()
891 // 0028 0100 US IMG Bits Allocated
892 // (in order no to be messed up by old ACR-NEMA RGB images)
893 // if (File::GetEntryValue(0x0028,0x0100) == "24")
896 std::string pixelType = GetPixelType();
897 if ( pixelType == "8U" || pixelType == "8S" )
901 if ( pixelType == "16U" || pixelType == "16S")
905 if ( pixelType == "32U" || pixelType == "32S")
909 if ( pixelType == "FD" )
913 gdcmWarningMacro( "Unknown pixel type");
918 * \brief Build the Pixel Type of the image.
919 * Possible values are:
920 * - 8U unsigned 8 bit,
922 * - 16U unsigned 16 bit,
923 * - 16S signed 16 bit,
924 * - 32U unsigned 32 bit,
925 * - 32S signed 32 bit,
926 * - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
927 * \warning 12 bit images appear as 16 bit.
928 * 24 bit images appear as 8 bit + photochromatic interp ="RGB "
929 * + Planar Configuration = 0
930 * @return 0S if nothing found. NOT USABLE file. The caller has to check
932 std::string File::GetPixelType()
934 std::string bitsAlloc = GetEntryValue(0x0028, 0x0100); // Bits Allocated
935 if ( bitsAlloc == GDCM_UNFOUND )
937 gdcmWarningMacro( "Missing Bits Allocated (0028,0100)");
938 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
941 if ( bitsAlloc == "64" )
945 else if ( bitsAlloc == "12" )
947 // It will be unpacked
950 else if ( bitsAlloc == "24" )
952 // (in order no to be messed up by old RGB images)
956 std::string sign = GetEntryValue(0x0028, 0x0103);//"Pixel Representation"
958 if (sign == GDCM_UNFOUND )
960 gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
961 sign = "U"; // default and arbitrary value, not to polute the output
963 else if ( sign == "0" )
971 return bitsAlloc + sign;
975 * \brief Check whether the pixels are signed (1) or UNsigned (0) data.
976 * \warning The method defaults to false (UNsigned) when tag 0028|0103
978 * The responsability of checking this value is left to the caller
979 * (NO transformation is performed on the pixels to make then >0)
980 * @return True when signed, false when UNsigned
982 bool File::IsSignedPixelData()
984 std::string strSign = GetEntryValue( 0x0028, 0x0103 );
985 if ( strSign == GDCM_UNFOUND )
987 gdcmWarningMacro( "(0028,0103) is supposed to be mandatory");
990 int sign = atoi( strSign.c_str() );
999 * \brief Check whether this a monochrome picture (gray levels) or not,
1000 * using "Photometric Interpretation" tag (0x0028,0x0004).
1001 * @return true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
1003 bool File::IsMonochrome()
1005 const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1006 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1007 || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1011 if ( PhotometricInterp == GDCM_UNFOUND )
1013 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1019 * \brief Check whether this a MONOCHROME1 picture (high values = dark)
1020 * or not using "Photometric Interpretation" tag (0x0028,0x0004).
1021 * @return true when "MONOCHROME1" . False otherwise.
1023 bool File::IsMonochrome1()
1025 const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1026 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1030 if ( PhotometricInterp == GDCM_UNFOUND )
1032 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1038 * \brief Check whether this a "PALETTE COLOR" picture or not by accessing
1039 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1040 * @return true when "PALETTE COLOR". False otherwise.
1042 bool File::IsPaletteColor()
1044 std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1045 if ( PhotometricInterp == "PALETTE COLOR " )
1049 if ( PhotometricInterp == GDCM_UNFOUND )
1051 gdcmWarningMacro( "Not found : Palette color (0028,0004)");
1057 * \brief Check whether this a "YBR_FULL" color picture or not by accessing
1058 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1059 * @return true when "YBR_FULL". False otherwise.
1061 bool File::IsYBRFull()
1063 std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1064 if ( PhotometricInterp == "YBR_FULL" )
1068 if ( PhotometricInterp == GDCM_UNFOUND )
1070 gdcmWarningMacro( "Not found : YBR Full (0028,0004)");
1076 * \brief tells us if LUT are used
1077 * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1078 * are NOT considered as LUT, since nobody knows
1079 * how to deal with them
1080 * Please warn me if you know sbdy that *does* know ... jprx
1081 * @return true if LUT Descriptors and LUT Tables were found
1085 // Check the presence of the LUT Descriptors, and LUT Tables
1087 if ( !GetDocEntry(0x0028,0x1101) )
1091 // LutDescriptorGreen
1092 if ( !GetDocEntry(0x0028,0x1102) )
1096 // LutDescriptorBlue
1097 if ( !GetDocEntry(0x0028,0x1103) )
1101 // Red Palette Color Lookup Table Data
1102 if ( !GetDocEntry(0x0028,0x1201) )
1106 // Green Palette Color Lookup Table Data
1107 if ( !GetDocEntry(0x0028,0x1202) )
1111 // Blue Palette Color Lookup Table Data
1112 if ( !GetDocEntry(0x0028,0x1203) )
1117 // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1118 // NOT taken into account, but we don't know how to use it ...
1123 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1125 * @return Lookup Table number of Bits , 0 by default
1126 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1127 * @ return bit number of each LUT item
1129 int File::GetLUTNbits()
1131 std::vector<std::string> tokens;
1134 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1135 // = Lookup Table Desc-Blue
1136 // Consistency already checked in GetLUTLength
1137 std::string lutDescription = GetEntryValue(0x0028,0x1101);
1138 if ( lutDescription == GDCM_UNFOUND )
1143 tokens.clear(); // clean any previous value
1144 Util::Tokenize ( lutDescription, tokens, "\\" );
1145 //LutLength=atoi(tokens[0].c_str());
1146 //LutDepth=atoi(tokens[1].c_str());
1148 lutNbits = atoi( tokens[2].c_str() );
1155 *\brief gets the info from 0028,1052 : Rescale Intercept
1156 * @return Rescale Intercept
1158 float File::GetRescaleIntercept()
1160 float resInter = 0.;
1161 /// 0028 1052 DS IMG Rescale Intercept
1162 const std::string &strRescInter = GetEntryValue(0x0028,0x1052);
1163 if ( strRescInter != GDCM_UNFOUND )
1165 if ( sscanf( strRescInter.c_str(), "%f ", &resInter) != 1 )
1167 // bug in the element 0x0028,0x1052
1168 gdcmWarningMacro( "Rescale Intercept (0028,1052) is empty." );
1176 *\brief gets the info from 0028,1053 : Rescale Slope
1177 * @return Rescale Slope
1179 float File::GetRescaleSlope()
1181 float resSlope = 1.;
1182 //0028 1053 DS IMG Rescale Slope
1183 std::string strRescSlope = GetEntryValue(0x0028,0x1053);
1184 if ( strRescSlope != GDCM_UNFOUND )
1186 if ( sscanf( strRescSlope.c_str(), "%f ", &resSlope) != 1 )
1188 // bug in the element 0x0028,0x1053
1189 gdcmWarningMacro( "Rescale Slope (0028,1053) is empty.");
1197 * \brief This function is intended to user who doesn't want
1198 * to have to manage a LUT and expects to get an RBG Pixel image
1199 * (or a monochrome one ...)
1200 * \warning to be used with GetImagePixels()
1201 * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1203 int File::GetNumberOfScalarComponents()
1205 if ( GetSamplesPerPixel() == 3 )
1210 // 0028 0100 US IMG Bits Allocated
1211 // (in order no to be messed up by old RGB images)
1212 if ( GetEntryValue(0x0028,0x0100) == "24" )
1217 std::string strPhotometricInterpretation = GetEntryValue(0x0028,0x0004);
1219 if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1221 if ( HasLUT() )// PALETTE COLOR is NOT enough
1231 // beware of trailing space at end of string
1232 // DICOM tags are never of odd length
1233 if ( strPhotometricInterpretation == GDCM_UNFOUND ||
1234 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1235 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1241 // we assume that *all* kinds of YBR are dealt with
1247 * \brief This function is intended to user that DOESN'T want
1248 * to get RGB pixels image when it's stored as a PALETTE COLOR image
1249 * - the (vtk) user is supposed to know how deal with LUTs -
1250 * \warning to be used with GetImagePixelsRaw()
1251 * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1253 int File::GetNumberOfScalarComponentsRaw()
1255 // 0028 0100 US IMG Bits Allocated
1256 // (in order no to be messed up by old RGB images)
1257 if ( File::GetEntryValue(0x0028,0x0100) == "24" )
1262 // we assume that *all* kinds of YBR are dealt with
1263 return GetSamplesPerPixel();
1267 * \brief Recover the offset (from the beginning of the file)
1268 * of *image* pixels (not *icone image* pixels, if any !)
1269 * @return Pixel Offset
1271 size_t File::GetPixelOffset()
1273 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1276 return pxlElement->GetOffset();
1280 gdcmDebugMacro( "Big trouble : Pixel Element ("
1281 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1287 * \brief Recover the pixel area length (in Bytes)
1288 * @return Pixel Element Length, as stored in the header
1289 * (NOT the memory space necessary to hold the Pixels
1290 * -in case of embeded compressed image-)
1291 * 0 : NOT USABLE file. The caller has to check.
1293 size_t File::GetPixelAreaLength()
1295 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1298 return pxlElement->GetLength();
1302 gdcmDebugMacro( "Big trouble : Pixel Element ("
1303 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1309 * \brief Adds the characteristics of a new element we want to anonymize
1310 * @param group Group number of the target tag.
1311 * @param elem Element number of the target tag.
1312 * @param value new value (string) to substitute with
1314 void File::AddAnonymizeElement (uint16_t group, uint16_t elem,
1315 std::string const &value)
1321 UserAnonymizeList.push_back(el);
1325 * \brief Overwrites in the file the values of the DicomElements
1328 void File::AnonymizeNoLoad()
1330 std::fstream *fp = new std::fstream(Filename.c_str(),
1331 std::ios::in | std::ios::out | std::ios::binary);
1335 uint32_t valLgth = 0;
1336 std::string *spaces;
1337 for (ListElements::iterator it = UserAnonymizeList.begin();
1338 it != UserAnonymizeList.end();
1341 d = GetDocEntry( (*it).Group, (*it).Elem);
1346 if ( dynamic_cast<SeqEntry *>(d) )
1348 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1352 offset = d->GetOffset();
1353 lgth = d->GetLength();
1356 spaces = new std::string( lgth-valLgth, ' ');
1357 (*it).Value = (*it).Value + *spaces;
1360 fp->seekp( offset, std::ios::beg );
1361 fp->write( (*it).Value.c_str(), lgth );
1369 * \brief anonymize a File (remove Patient's personal info passed with
1370 * AddAnonymizeElement()
1371 * \note You cannot Anonymize a BinEntry (to be fixed)
1373 bool File::AnonymizeFile()
1375 // If Anonymisation list is empty, let's perform some basic anonymization
1376 if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1378 // If exist, replace by spaces
1379 SetValEntry (" ",0x0010, 0x2154); // Telephone
1380 SetValEntry (" ",0x0010, 0x1040); // Adress
1381 SetValEntry (" ",0x0010, 0x0020); // Patient ID
1383 DocEntry* patientNameHE = GetDocEntry (0x0010, 0x0010);
1385 if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1387 std::string studyInstanceUID = GetEntryValue (0x0020, 0x000d);
1388 if ( studyInstanceUID != GDCM_UNFOUND )
1390 SetValEntry(studyInstanceUID, 0x0010, 0x0010);
1394 SetValEntry("anonymized", 0x0010, 0x0010);
1401 for (ListElements::iterator it = UserAnonymizeList.begin();
1402 it != UserAnonymizeList.end();
1405 d = GetDocEntry( (*it).Group, (*it).Elem);
1410 if ( dynamic_cast<SeqEntry *>(d) )
1412 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1416 if ( dynamic_cast<BinEntry *>(d) )
1418 gdcmWarningMacro( "To 'Anonymize' a BinEntry, better use AnonymizeNoLoad (FIXME) ");
1422 SetValEntry ((*it).Value, (*it).Group, (*it).Elem);
1426 // In order to make definitively impossible any further identification
1427 // remove or replace all the stuff that contains a Date
1429 //0008 0012 DA ID Instance Creation Date
1430 //0008 0020 DA ID Study Date
1431 //0008 0021 DA ID Series Date
1432 //0008 0022 DA ID Acquisition Date
1433 //0008 0023 DA ID Content Date
1434 //0008 0024 DA ID Overlay Date
1435 //0008 0025 DA ID Curve Date
1436 //0008 002a DT ID Acquisition Datetime
1437 //0018 9074 DT ACQ Frame Acquisition Datetime
1438 //0018 9151 DT ACQ Frame Reference Datetime
1439 //0018 a002 DT ACQ Contribution Date Time
1440 //0020 3403 SH REL Modified Image Date (RET)
1441 //0032 0032 DA SDY Study Verified Date
1442 //0032 0034 DA SDY Study Read Date
1443 //0032 1000 DA SDY Scheduled Study Start Date
1444 //0032 1010 DA SDY Scheduled Study Stop Date
1445 //0032 1040 DA SDY Study Arrival Date
1446 //0032 1050 DA SDY Study Completion Date
1447 //0038 001a DA VIS Scheduled Admission Date
1448 //0038 001c DA VIS Scheduled Discharge Date
1449 //0038 0020 DA VIS Admitting Date
1450 //0038 0030 DA VIS Discharge Date
1451 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1452 //0040 0004 DA PRC Scheduled Procedure Step End Date
1453 //0040 0244 DA PRC Performed Procedure Step Start Date
1454 //0040 0250 DA PRC Performed Procedure Step End Date
1455 //0040 2004 DA PRC Issue Date of Imaging Service Request
1456 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1457 //0040 4011 DT PRC Expected Completion Date and Time
1458 //0040 a030 DT PRC Verification Date Time
1459 //0040 a032 DT PRC Observation Date Time
1460 //0040 a120 DT PRC DateTime
1461 //0040 a121 DA PRC Date
1462 //0040 a13a DT PRC Referenced Datetime
1463 //0070 0082 DA ??? Presentation Creation Date
1464 //0100 0420 DT ??? SOP Autorization Date and Time
1465 //0400 0105 DT ??? Digital Signature DateTime
1466 //2100 0040 DA PJ Creation Date
1467 //3006 0008 DA SSET Structure Set Date
1468 //3008 0024 DA ??? Treatment Control Point Date
1469 //3008 0054 DA ??? First Treatment Date
1470 //3008 0056 DA ??? Most Recent Treatment Date
1471 //3008 0162 DA ??? Safe Position Exit Date
1472 //3008 0166 DA ??? Safe Position Return Date
1473 //3008 0250 DA ??? Treatment Date
1474 //300a 0006 DA RT RT Plan Date
1475 //300a 022c DA RT Air Kerma Rate Reference Date
1476 //300e 0004 DA RT Review Date
1482 * \brief Performs some consistency checking on various 'File related'
1483 * (as opposed to 'DicomDir related') entries
1484 * then writes in a file all the (Dicom Elements) included the Pixels
1485 * @param fileName file name to write to
1486 * @param writetype type of the file to be written
1487 * (ACR, ExplicitVR, ImplicitVR)
1489 bool File::Write(std::string fileName, FileType writetype)
1491 std::ofstream *fp = new std::ofstream(fileName.c_str(),
1492 std::ios::out | std::ios::binary);
1495 gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1499 // Entry : 0002|0000 = group length -> recalculated
1500 ValEntry*e0000 = GetValEntry(0x0002,0x0000);
1503 std::ostringstream sLen;
1504 sLen << ComputeGroup0002Length( );
1505 e0000->SetValue(sLen.str());
1508 int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1511 // no (GrPixel, NumPixel) element
1512 std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1513 s_lgPix = Util::DicomString( s_lgPix.c_str() );
1514 InsertValEntry(s_lgPix,GrPixel, 0x0000);
1517 Document::WriteContent(fp, writetype);
1525 //-----------------------------------------------------------------------------
1529 //-----------------------------------------------------------------------------
1532 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1533 * Compute the RLE extra information and store it in \ref RLEInfo
1534 * for later pixel retrieval usage.
1536 void File::ComputeRLEInfo()
1538 std::string ts = GetTransferSyntax();
1539 if ( !Global::GetTS()->IsRLELossless(ts) )
1544 // Encoded pixel data: for the time being we are only concerned with
1545 // Jpeg or RLE Pixel data encodings.
1546 // As stated in PS 3.5-2003, section 8.2 p44:
1547 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1548 // value representation OB is used".
1549 // Hence we expect an OB value representation. Concerning OB VR,
1550 // the section PS 3.5-2003, section A.4.c p 58-59, states:
1551 // "For the Value Representations OB and OW, the encoding shall meet the
1552 // following specifications depending on the Data element tag:"
1554 // - the first item in the sequence of items before the encoded pixel
1555 // data stream shall be basic offset table item. The basic offset table
1556 // item value, however, is not required to be present"
1557 ReadAndSkipEncapsulatedBasicOffsetTable();
1559 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1560 // Loop on the individual frame[s] and store the information
1561 // on the RLE fragments in a RLEFramesInfo.
1562 // Note: - when only a single frame is present, this is a
1564 // - when more than one frame are present, then we are in
1565 // the case of a multi-frame image.
1567 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1569 // Parse the RLE Header and store the corresponding RLE Segment
1570 // Offset Table information on fragments of this current Frame.
1571 // Note that the fragment pixels themselves are not loaded
1572 // (but just skipped).
1573 long frameOffset = Fp->tellg();
1575 uint32_t nbRleSegments = ReadInt32();
1576 if ( nbRleSegments > 16 )
1578 // There should be at most 15 segments (refer to RLEFrame class)
1579 gdcmWarningMacro( "Too many segments.");
1582 uint32_t rleSegmentOffsetTable[16];
1583 for( int k = 1; k <= 15; k++ )
1585 rleSegmentOffsetTable[k] = ReadInt32();
1588 // Deduce from both RLE Header and frameLength
1589 // the fragment length, and again store this info
1590 // in a RLEFramesInfo.
1591 long rleSegmentLength[15];
1592 // skipping (not reading) RLE Segments
1593 if ( nbRleSegments > 1)
1595 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1597 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
1598 - rleSegmentOffsetTable[k];
1599 SkipBytes(rleSegmentLength[k]);
1603 rleSegmentLength[nbRleSegments] = frameLength
1604 - rleSegmentOffsetTable[nbRleSegments];
1605 SkipBytes(rleSegmentLength[nbRleSegments]);
1607 // Store the collected info
1608 RLEFrame *newFrame = new RLEFrame;
1609 newFrame->SetNumberOfFragments(nbRleSegments);
1610 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1612 newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1613 newFrame->SetLength(uk,rleSegmentLength[uk]);
1615 RLEInfo->AddFrame(newFrame);
1618 // Make sure that we encounter a 'Sequence Delimiter Item'
1619 // at the end of the item :
1620 if ( !ReadTag(0xfffe, 0xe0dd) )
1622 gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1627 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1628 * Compute the jpeg extra information (fragment[s] offset[s] and
1629 * length) and store it[them] in \ref JPEGInfo for later pixel
1632 void File::ComputeJPEGFragmentInfo()
1634 // If you need to, look for comments of ComputeRLEInfo().
1635 std::string ts = GetTransferSyntax();
1636 if ( ! Global::GetTS()->IsJPEG(ts) )
1641 ReadAndSkipEncapsulatedBasicOffsetTable();
1643 // Loop on the fragments[s] and store the parsed information in a
1645 long fragmentLength;
1646 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1648 long fragmentOffset = Fp->tellg();
1650 // Store the collected info
1651 JPEGFragment *newFragment = new JPEGFragment;
1652 newFragment->SetOffset(fragmentOffset);
1653 newFragment->SetLength(fragmentLength);
1654 JPEGInfo->AddFragment(newFragment);
1656 SkipBytes(fragmentLength);
1659 // Make sure that we encounter a 'Sequence Delimiter Item'
1660 // at the end of the item :
1661 if ( !ReadTag(0xfffe, 0xe0dd) )
1663 gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1668 * \brief Assuming the internal file pointer \ref Document::Fp
1669 * is placed at the beginning of a tag check whether this
1670 * tag is (TestGroup, TestElem).
1671 * \warning On success the internal file pointer \ref Document::Fp
1672 * is modified to point after the tag.
1673 * On failure (i.e. when the tag wasn't the expected tag
1674 * (TestGroup, TestElem) the internal file pointer
1675 * \ref Document::Fp is restored to it's original position.
1676 * @param testGroup The expected group of the tag.
1677 * @param testElem The expected Element of the tag.
1678 * @return True on success, false otherwise.
1680 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1682 long positionOnEntry = Fp->tellg();
1683 long currentPosition = Fp->tellg(); // On debugging purposes
1685 // Read the Item Tag group and element, and make
1686 // sure they are what we expected:
1687 uint16_t itemTagGroup;
1688 uint16_t itemTagElem;
1691 itemTagGroup = ReadInt16();
1692 itemTagElem = ReadInt16();
1694 catch ( FormatError /*e*/ )
1696 //std::cerr << e << std::endl;
1699 if ( itemTagGroup != testGroup || itemTagElem != testElem )
1701 gdcmWarningMacro( "Wrong Item Tag found:"
1702 << " We should have found tag ("
1703 << std::hex << testGroup << "," << testElem << ")" << std::endl
1704 << " but instead we encountered tag ("
1705 << std::hex << itemTagGroup << "," << itemTagElem << ")"
1706 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
1708 Fp->seekg(positionOnEntry, std::ios::beg);
1716 * \brief Assuming the internal file pointer \ref Document::Fp
1717 * is placed at the beginning of a tag (TestGroup, TestElement),
1718 * read the length associated to the Tag.
1719 * \warning On success the internal file pointer \ref Document::Fp
1720 * is modified to point after the tag and it's length.
1721 * On failure (i.e. when the tag wasn't the expected tag
1722 * (TestGroup, TestElement) the internal file pointer
1723 * \ref Document::Fp is restored to it's original position.
1724 * @param testGroup The expected Group of the tag.
1725 * @param testElem The expected Element of the tag.
1726 * @return On success returns the length associated to the tag. On failure
1729 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1732 if ( !ReadTag(testGroup, testElem) )
1737 //// Then read the associated Item Length
1738 long currentPosition = Fp->tellg();
1739 uint32_t itemLength = ReadInt32();
1741 gdcmWarningMacro( "Basic Item Length is: "
1742 << itemLength << std::endl
1743 << " at address: " << std::hex << (unsigned int)currentPosition);
1749 * \brief When parsing the Pixel Data of an encapsulated file, read
1750 * the basic offset table (when present, and BTW dump it).
1752 void File::ReadAndSkipEncapsulatedBasicOffsetTable()
1754 //// Read the Basic Offset Table Item Tag length...
1755 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1757 // When present, read the basic offset table itself.
1758 // Notes: - since the presence of this basic offset table is optional
1759 // we can't rely on it for the implementation, and we will simply
1760 // trash it's content (when present).
1761 // - still, when present, we could add some further checks on the
1762 // lengths, but we won't bother with such fuses for the time being.
1763 if ( itemLength != 0 )
1765 char *basicOffsetTableItemValue = new char[itemLength + 1];
1766 Fp->read(basicOffsetTableItemValue, itemLength);
1769 for (unsigned int i=0; i < itemLength; i += 4 )
1771 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
1773 gdcmWarningMacro( "Read one length: " <<
1774 std::hex << individualLength );
1778 delete[] basicOffsetTableItemValue;
1782 // These are the deprecated method that one day should be removed (after the next release)
1784 #ifndef GDCM_LEGACY_REMOVE
1786 * \brief Constructor (DEPRECATED : temporaryly kept not to break the API)
1787 * @param filename name of the file whose header we want to analyze
1788 * @deprecated do not use any longer
1790 File::File( std::string const &filename )
1793 RLEInfo = new RLEFramesInfo;
1794 JPEGInfo = new JPEGFragmentsInfo;
1796 SetFileName( filename );
1797 Load( ); // gdcm::Document is first Loaded, then the 'File part'
1801 * \brief Loader. (DEPRECATED : temporaryly kept not to break the API)
1802 * @param fileName file to be open for parsing
1803 * @return false if file cannot be open or no swap info was found,
1804 * or no tag was found.
1805 * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
1807 bool File::Load( std::string const &fileName )
1809 GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
1811 SetFileName( fileName );
1812 if ( ! this->Document::Load( ) )
1815 return DoTheLoadingJob( );
1819 //-----------------------------------------------------------------------------
1822 //-----------------------------------------------------------------------------
1823 } // end namespace gdcm