1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2005/09/05 08:20:08 $
7 Version: $Revision: 1.266 $
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 ...
77 // Found Values are : L\P
84 // (0020|0037) [Image Orientation (Patient)] [1\0\0\0\1\0 ]
87 // ---------------------------------------------------------------
90 #include "gdcmGlobal.h"
92 #include "gdcmDebug.h"
94 #include "gdcmValEntry.h"
95 #include "gdcmBinEntry.h"
96 #include "gdcmSeqEntry.h"
97 #include "gdcmRLEFramesInfo.h"
98 #include "gdcmJPEGFragmentsInfo.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
124 * \brief Canonical destructor.
134 //-----------------------------------------------------------------------------
138 * @return false if file cannot be open or no swap info was found,
139 * or no tag was found.
143 if ( ! this->Document::Load( ) )
146 return DoTheLoadingJob( );
150 * \brief Does the Loading Job (internal use only)
151 * @return false if file cannot be open or no swap info was found,
152 * or no tag was found.
154 bool File::DoTheLoadingJob( )
157 // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
158 // We may encounter the 'RETired' (0x0028, 0x0200) tag
159 // (Image Location") . This entry contains the number of
160 // the group that contains the pixel data (hence the "Pixel Data"
161 // is found by indirection through the "Image Location").
162 // Inside the group pointed by "Image Location" the searched element
163 // is conventionally the element 0x0010 (when the norm is respected).
164 // When the "Image Location" is missing we default to group 0x7fe0.
165 // Note: this IS the right place for the code
168 const std::string &imgLocation = GetEntryValue(0x0028, 0x0200);
169 if ( imgLocation == GDCM_UNFOUND )
176 GrPixel = (uint16_t) atoi( imgLocation.c_str() );
179 // sometimes Image Location value doesn't follow
180 // the supposed processor endianness.
181 // see gdcmData/cr172241.dcm
182 if ( GrPixel == 0xe07f )
187 if ( GrPixel != 0x7fe0 )
189 // This is a kludge for old dirty Philips imager.
197 // Now, we know GrPixel and NumPixel.
198 // Let's create a VirtualDictEntry to allow a further VR modification
199 // and force VR to match with BitsAllocated.
200 DocEntry *entry = GetDocEntry(GrPixel, NumPixel);
203 // Compute the RLE or JPEG info
205 const std::string &ts = GetTransferSyntax();
206 Fp->seekg( entry->GetOffset(), std::ios::beg );
207 if ( Global::GetTS()->IsRLELossless(ts) )
209 else if ( Global::GetTS()->IsJPEG(ts) )
210 ComputeJPEGFragmentInfo();
213 // Create a new BinEntry to change the DictEntry
214 // The changed DictEntry will have
215 // - a correct PixelVR OB or OW)
216 // - the name to "Pixel Data"
217 BinEntry *oldEntry = dynamic_cast<BinEntry *>(entry);
221 // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
222 // more than 8 (i.e 12, 16) is a 'O Words'
223 if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 )
228 // Change only made if usefull
229 if ( PixelVR != oldEntry->GetVR() )
231 DictEntry* newDict = NewVirtualDictEntry(GrPixel,NumPixel,
232 PixelVR,"1","Pixel Data");
234 BinEntry *newEntry = new BinEntry(newDict);
235 newEntry->Copy(entry);
236 newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
237 oldEntry->SetSelfArea(false);
239 RemoveEntry(oldEntry);
247 * \brief This predicate, based on hopefully reasonable heuristics,
248 * decides whether or not the current File was properly parsed
249 * and contains the mandatory information for being considered as
250 * a well formed and usable Dicom/Acr File.
251 * @return true when File is the one of a reasonable Dicom/Acr file,
254 bool File::IsReadable()
256 if ( !Document::IsReadable() )
261 const std::string &res = GetEntryValue(0x0028, 0x0005);
262 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
264 gdcmWarningMacro("Wrong Image Dimensions" << res);
265 return false; // Image Dimensions
267 bool b0028_0100 = true;
268 if ( !GetDocEntry(0x0028, 0x0100) )
270 gdcmWarningMacro("Bits Allocated (0028|0100) not found");
271 //return false; // "Bits Allocated"
274 bool b0028_0101 = true;
275 if ( !GetDocEntry(0x0028, 0x0101) )
277 gdcmWarningMacro("Bits Stored (0028|0101) not found");
278 //return false; // "Bits Stored"
281 bool b0028_0102 = true;
282 if ( !GetDocEntry(0x0028, 0x0102) )
284 gdcmWarningMacro("Hight Bit (0028|0102) not found");
285 //return false; // "High Bit"
288 bool b0028_0103 = true;
289 if ( !GetDocEntry(0x0028, 0x0103) )
291 gdcmWarningMacro("Pixel Representation (0028|0103) not found");
292 //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
296 if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
298 gdcmWarningMacro("Too much mandatory Tags missing !");
302 if ( !GetDocEntry(GrPixel, NumPixel) )
304 gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
305 GrPixel << "|" << NumPixel << "not found");
306 return false; // Pixel Dicom Element not found :-(
312 * \brief gets the info from 0020,0013 : Image Number else 0.
313 * @return image number
315 int File::GetImageNumber()
317 //0020 0013 : Image Number
318 std::string strImNumber = GetEntryValue(0x0020,0x0013);
319 if ( strImNumber != GDCM_UNFOUND )
321 return atoi( strImNumber.c_str() );
327 * \brief gets the info from 0008,0060 : Modality
328 * @return Modality Type
330 ModalityType File::GetModality()
332 // 0008 0060 : Modality
333 std::string strModality = GetEntryValue(0x0008,0x0060);
334 if ( strModality != GDCM_UNFOUND )
336 if ( strModality.find("AU") < strModality.length()) return AU;
337 else if ( strModality.find("AS") < strModality.length()) return AS;
338 else if ( strModality.find("BI") < strModality.length()) return BI;
339 else if ( strModality.find("CF") < strModality.length()) return CF;
340 else if ( strModality.find("CP") < strModality.length()) return CP;
341 else if ( strModality.find("CR") < strModality.length()) return CR;
342 else if ( strModality.find("CT") < strModality.length()) return CT;
343 else if ( strModality.find("CS") < strModality.length()) return CS;
344 else if ( strModality.find("DD") < strModality.length()) return DD;
345 else if ( strModality.find("DF") < strModality.length()) return DF;
346 else if ( strModality.find("DG") < strModality.length()) return DG;
347 else if ( strModality.find("DM") < strModality.length()) return DM;
348 else if ( strModality.find("DS") < strModality.length()) return DS;
349 else if ( strModality.find("DX") < strModality.length()) return DX;
350 else if ( strModality.find("ECG") < strModality.length()) return ECG;
351 else if ( strModality.find("EPS") < strModality.length()) return EPS;
352 else if ( strModality.find("FA") < strModality.length()) return FA;
353 else if ( strModality.find("FS") < strModality.length()) return FS;
354 else if ( strModality.find("HC") < strModality.length()) return HC;
355 else if ( strModality.find("HD") < strModality.length()) return HD;
356 else if ( strModality.find("LP") < strModality.length()) return LP;
357 else if ( strModality.find("LS") < strModality.length()) return LS;
358 else if ( strModality.find("MA") < strModality.length()) return MA;
359 else if ( strModality.find("MR") < strModality.length()) return MR;
360 else if ( strModality.find("NM") < strModality.length()) return NM;
361 else if ( strModality.find("OT") < strModality.length()) return OT;
362 else if ( strModality.find("PT") < strModality.length()) return PT;
363 else if ( strModality.find("RF") < strModality.length()) return RF;
364 else if ( strModality.find("RG") < strModality.length()) return RG;
365 else if ( strModality.find("RTDOSE")
366 < strModality.length()) return RTDOSE;
367 else if ( strModality.find("RTIMAGE")
368 < strModality.length()) return RTIMAGE;
369 else if ( strModality.find("RTPLAN")
370 < strModality.length()) return RTPLAN;
371 else if ( strModality.find("RTSTRUCT")
372 < strModality.length()) return RTSTRUCT;
373 else if ( strModality.find("SM") < strModality.length()) return SM;
374 else if ( strModality.find("ST") < strModality.length()) return ST;
375 else if ( strModality.find("TG") < strModality.length()) return TG;
376 else if ( strModality.find("US") < strModality.length()) return US;
377 else if ( strModality.find("VF") < strModality.length()) return VF;
378 else if ( strModality.find("XA") < strModality.length()) return XA;
379 else if ( strModality.find("XC") < strModality.length()) return XC;
383 /// \todo throw error return value ???
384 /// specified <> unknown in our database
392 * \brief Retrieve the number of columns of image.
393 * @return The encountered size when found, 0 by default.
394 * 0 means the file is NOT USABLE. The caller will have to check
398 const std::string &strSize = GetEntryValue(0x0028,0x0011);
399 if ( strSize == GDCM_UNFOUND )
403 return atoi( strSize.c_str() );
407 * \brief Retrieve the number of lines of image.
408 * \warning The defaulted value is 1 as opposed to File::GetXSize()
409 * @return The encountered size when found, 1 by default
410 * (The ACR-NEMA file contains a Signal, not an Image).
414 const std::string &strSize = GetEntryValue(0x0028,0x0010);
415 if ( strSize != GDCM_UNFOUND )
417 return atoi( strSize.c_str() );
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 const std::string &strSize = GetEntryValue(0x0028,0x0008);
443 if ( strSize != GDCM_UNFOUND )
445 return atoi( strSize.c_str() );
448 // We then consider the "Planes" entry as the third dimension
449 const std::string &strSize2 = GetEntryValue(0x0028,0x0012);
450 if ( strSize2 != GDCM_UNFOUND )
452 return atoi( strSize2.c_str() );
458 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
459 * then 0028,0030 : Pixel Spacing
461 * @return X dimension of a pixel
463 float File::GetXSpacing()
465 float xspacing = 1.0;
466 float yspacing = 1.0;
469 // To follow David Clunie's advice, we first check ImagerPixelSpacing
471 const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
472 if ( strImagerPixelSpacing != GDCM_UNFOUND )
474 if ( ( nbValues = sscanf( strImagerPixelSpacing.c_str(),
475 "%f\\%f", &yspacing, &xspacing)) != 2 )
477 // if no values, xspacing is set to 1.0
480 // if single value is found, xspacing is defaulted to yspacing
484 if ( xspacing == 0.0 )
491 const std::string &strSpacing = GetEntryValue(0x0028,0x0030);
493 if ( strSpacing == GDCM_UNFOUND )
495 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
499 if ( ( nbValues = sscanf( strSpacing.c_str(),
500 "%f \\%f ", &yspacing, &xspacing)) != 2 )
502 // if no values, xspacing is set to 1.0
505 // if single value is found, xspacing is defaulted to yspacing
509 if ( xspacing == 0.0 )
515 // to avoid troubles with David Clunie's-like images (at least one)
516 if ( xspacing == 0. && yspacing == 0.)
521 gdcmWarningMacro("gdcmData/CT-MONO2-8-abdo.dcm-like problem");
522 // seems to be a bug in the header ...
523 nbValues = sscanf( strSpacing.c_str(), "%f \\0\\%f ", &yspacing, &xspacing);
524 gdcmAssertMacro( nbValues == 2 );
531 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
532 * then from 0028,0030 : Pixel Spacing
534 * @return Y dimension of a pixel
536 float File::GetYSpacing()
540 // To follow David Clunie's advice, we first check ImagerPixelSpacing
542 const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
543 if ( strImagerPixelSpacing != GDCM_UNFOUND )
545 nbValues = sscanf( strImagerPixelSpacing.c_str(), "%f", &yspacing);
547 // if sscanf cannot read any float value, it won't affect yspacing
551 if ( yspacing == 0.0 )
557 std::string strSpacing = GetEntryValue(0x0028,0x0030);
558 if ( strSpacing == GDCM_UNFOUND )
560 gdcmWarningMacro("Unfound Pixel Spacing (0028,0030)");
564 // if sscanf cannot read any float value, it won't affect yspacing
565 nbValues = sscanf( strSpacing.c_str(), "%f", &yspacing);
567 // if no values, yspacing is set to 1.0
571 if ( yspacing == 0.0 )
578 * \brief gets the info from 0018,0088 : Space Between Slices
579 * else from 0018,0050 : Slice Thickness
581 * @return Z dimension of a voxel-to be
583 float File::GetZSpacing()
585 // Spacing Between Slices : distance between the middle of 2 slices
587 // jointives (Spacing between Slices = Slice Thickness)
588 // overlapping (Spacing between Slices < Slice Thickness)
589 // disjointes (Spacing between Slices > Slice Thickness)
590 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
591 // It only concerns the MRI guys, not people wanting to visualize volumes
592 // If Spacing Between Slices is missing,
593 // we suppose slices joint together
595 const std::string &strSpacingBSlices = GetEntryValue(0x0018,0x0088);
597 if ( strSpacingBSlices == GDCM_UNFOUND )
599 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
600 const std::string &strSliceThickness = GetEntryValue(0x0018,0x0050);
601 if ( strSliceThickness == GDCM_UNFOUND )
603 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
608 // if no 'Spacing Between Slices' is found,
609 // we assume slices join together
610 // (no overlapping, no interslice gap)
611 // if they don't, we're fucked up
612 return (float)atof( strSliceThickness.c_str() );
616 return (float)atof( strSpacingBSlices.c_str() );
620 * \brief gets the info from 0020,0032 : Image Position Patient
621 * else from 0020,0030 : Image Position (RET)
623 * @return up-left image corner X position
625 float File::GetXOrigin()
627 float xImPos, yImPos, zImPos;
628 std::string strImPos = GetEntryValue(0x0020,0x0032);
630 if ( strImPos == GDCM_UNFOUND )
632 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
633 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
634 if ( strImPos == GDCM_UNFOUND )
636 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
641 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
650 * \brief gets the info from 0020,0032 : Image Position Patient
651 * else from 0020,0030 : Image Position (RET)
653 * @return up-left image corner Y position
655 float File::GetYOrigin()
657 float xImPos, yImPos, zImPos;
658 std::string strImPos = GetEntryValue(0x0020,0x0032);
660 if ( strImPos == GDCM_UNFOUND)
662 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
663 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
664 if ( strImPos == GDCM_UNFOUND )
666 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
671 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
680 * \brief gets the info from 0020,0032 : Image Position Patient
681 * else from 0020,0030 : Image Position (RET)
682 * else from 0020,1041 : Slice Location
683 * else from 0020,0050 : Location
685 * @return up-left image corner Z position
687 float File::GetZOrigin()
689 float xImPos, yImPos, zImPos;
690 std::string strImPos = GetEntryValue(0x0020,0x0032);
692 if ( strImPos != GDCM_UNFOUND )
694 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3)
696 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
697 return 0.; // bug in the element 0x0020,0x0032
705 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
706 if ( strImPos != GDCM_UNFOUND )
708 if ( sscanf( strImPos.c_str(),
709 "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos ) != 3 )
711 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
712 return 0.; // bug in the element 0x0020,0x0032
720 // for *very* old ACR-NEMA images
721 std::string strSliceLocation = GetEntryValue(0x0020,0x1041);
722 if ( strSliceLocation != GDCM_UNFOUND )
724 if ( sscanf( strSliceLocation.c_str(), "%f ", &zImPos) != 1)
726 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
727 return 0.; // bug in the element 0x0020,0x1041
734 gdcmWarningMacro( "Unfound Slice Location (0020,1041)");
736 std::string strLocation = GetEntryValue(0x0020,0x0050);
737 if ( strLocation != GDCM_UNFOUND )
739 if ( sscanf( strLocation.c_str(), "%f ", &zImPos) != 1 )
741 gdcmWarningMacro( "Wrong Location (0020,0050)");
742 return 0.; // bug in the element 0x0020,0x0050
749 gdcmWarningMacro( "Unfound Location (0020,0050)");
751 return 0.; // Hopeless
755 * \brief gets the info from 0020,0037 : Image Orientation Patient
756 * (needed to organize DICOM files based on their x,y,z position)
757 * @param iop adress of the (6)float array to receive values
758 * @return cosines of image orientation patient
760 bool File::GetImageOrientationPatient( float iop[6] )
762 std::string strImOriPat;
763 //iop is supposed to be float[6]
764 iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
766 // 0020 0037 DS REL Image Orientation (Patient)
767 if ( (strImOriPat = GetEntryValue(0x0020,0x0037)) != GDCM_UNFOUND )
769 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
770 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
772 gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037). Less than 6 values were found." );
777 // 0020 0035 DS REL Image Orientation (RET)
778 else if ( (strImOriPat = GetEntryValue(0x0020,0x0035)) != GDCM_UNFOUND )
780 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
781 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
783 gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). Less than 6 values were found." );
791 * \brief Retrieve the number of Bits Stored (actually used)
792 * (as opposed to number of Bits Allocated)
793 * @return The encountered number of Bits Stored, 0 by default.
794 * 0 means the file is NOT USABLE. The caller has to check it !
796 int File::GetBitsStored()
798 std::string strSize = GetEntryValue( 0x0028, 0x0101 );
799 if ( strSize == GDCM_UNFOUND )
801 gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
802 return 0; // It's supposed to be mandatory
803 // the caller will have to check
805 return atoi( strSize.c_str() );
809 * \brief Retrieve the number of Bits Allocated
810 * (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
811 * @return The encountered Number of Bits Allocated, 0 by default.
812 * 0 means the file is NOT USABLE. The caller has to check it !
814 int File::GetBitsAllocated()
816 std::string strSize = GetEntryValue(0x0028,0x0100);
817 if ( strSize == GDCM_UNFOUND )
819 gdcmWarningMacro( "(0028,0100) is supposed to be mandatory");
820 return 0; // It's supposed to be mandatory
821 // the caller will have to check
823 return atoi( strSize.c_str() );
827 * \brief Retrieve the high bit position.
828 * \warning The method defaults to 0 when information is missing.
829 * The responsability of checking this value is left to the caller.
830 * @return The high bit position when present. 0 when missing.
832 int File::GetHighBitPosition()
834 std::string strSize = GetEntryValue( 0x0028, 0x0102 );
835 if ( strSize == GDCM_UNFOUND )
837 gdcmWarningMacro( "(0028,0102) is supposed to be mandatory");
840 return atoi( strSize.c_str() );
844 * \brief Retrieve the number of Samples Per Pixel
845 * (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
846 * @return The encountered number of Samples Per Pixel, 1 by default.
847 * (we assume Gray level Pixels)
849 int File::GetSamplesPerPixel()
851 const std::string &strSize = GetEntryValue(0x0028,0x0002);
852 if ( strSize == GDCM_UNFOUND )
854 gdcmWarningMacro( "(0028,0002) is supposed to be mandatory");
855 return 1; // Well, it's supposed to be mandatory ...
856 // but sometimes it's missing : *we* assume Gray pixels
858 return atoi( strSize.c_str() );
862 * \brief Retrieve the Planar Configuration for RGB images
863 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
864 * @return The encountered Planar Configuration, 0 by default.
866 int File::GetPlanarConfiguration()
868 std::string strSize = GetEntryValue(0x0028,0x0006);
869 if ( strSize == GDCM_UNFOUND )
871 gdcmWarningMacro( "Not found : Planar Configuration (0028,0006)");
874 return atoi( strSize.c_str() );
878 * \brief Return the size (in bytes) of a single pixel of data.
879 * @return The size in bytes of a single pixel of data; 0 by default
880 * 0 means the file is NOT USABLE; the caller will have to check
882 int File::GetPixelSize()
884 // 0028 0100 US IMG Bits Allocated
885 // (in order no to be messed up by old ACR-NEMA RGB images)
886 // if (File::GetEntryValue(0x0028,0x0100) == "24")
889 std::string pixelType = GetPixelType();
890 if ( pixelType == "8U" || pixelType == "8S" )
894 if ( pixelType == "16U" || pixelType == "16S")
898 if ( pixelType == "32U" || pixelType == "32S")
902 if ( pixelType == "FD" )
906 gdcmWarningMacro( "Unknown pixel type");
911 * \brief Build the Pixel Type of the image.
912 * Possible values are:
913 * - 8U unsigned 8 bit,
915 * - 16U unsigned 16 bit,
916 * - 16S signed 16 bit,
917 * - 32U unsigned 32 bit,
918 * - 32S signed 32 bit,
919 * - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
920 * \warning 12 bit images appear as 16 bit.
921 * 24 bit images appear as 8 bit + photochromatic interp ="RGB "
922 * + Planar Configuration = 0
923 * @return 0S if nothing found. NOT USABLE file. The caller has to check
925 std::string File::GetPixelType()
927 std::string bitsAlloc = GetEntryValue(0x0028, 0x0100); // Bits Allocated
928 if ( bitsAlloc == GDCM_UNFOUND )
930 gdcmWarningMacro( "Missing Bits Allocated (0028,0100)");
931 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
934 if ( bitsAlloc == "64" )
938 else if ( bitsAlloc == "12" )
940 // It will be unpacked
943 else if ( bitsAlloc == "24" )
945 // (in order no to be messed up by old RGB images)
949 std::string sign = GetEntryValue(0x0028, 0x0103);//"Pixel Representation"
951 if (sign == GDCM_UNFOUND )
953 gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
954 sign = "U"; // default and arbitrary value, not to polute the output
956 else if ( sign == "0" )
964 return bitsAlloc + sign;
968 * \brief Check whether the pixels are signed (1) or UNsigned (0) data.
969 * \warning The method defaults to false (UNsigned) when tag 0028|0103
971 * The responsability of checking this value is left to the caller
972 * (NO transformation is performed on the pixels to make then >0)
973 * @return True when signed, false when UNsigned
975 bool File::IsSignedPixelData()
977 std::string strSign = GetEntryValue( 0x0028, 0x0103 );
978 if ( strSign == GDCM_UNFOUND )
980 gdcmWarningMacro( "(0028,0103) is supposed to be mandatory");
983 int sign = atoi( strSign.c_str() );
992 * \brief Check whether this a monochrome picture (gray levels) or not,
993 * using "Photometric Interpretation" tag (0x0028,0x0004).
994 * @return true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
996 bool File::IsMonochrome()
998 const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
999 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1000 || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1004 if ( PhotometricInterp == GDCM_UNFOUND )
1006 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1012 * \brief Check whether this a MONOCHROME1 picture (high values = dark)
1013 * or not using "Photometric Interpretation" tag (0x0028,0x0004).
1014 * @return true when "MONOCHROME1" . False otherwise.
1016 bool File::IsMonochrome1()
1018 const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1019 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1023 if ( PhotometricInterp == GDCM_UNFOUND )
1025 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1031 * \brief Check whether this a "PALETTE COLOR" picture or not by accessing
1032 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1033 * @return true when "PALETTE COLOR". False otherwise.
1035 bool File::IsPaletteColor()
1037 std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1038 if ( PhotometricInterp == "PALETTE COLOR " )
1042 if ( PhotometricInterp == GDCM_UNFOUND )
1044 gdcmWarningMacro( "Not found : Palette color (0028,0004)");
1050 * \brief Check whether this a "YBR_FULL" color picture or not by accessing
1051 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1052 * @return true when "YBR_FULL". False otherwise.
1054 bool File::IsYBRFull()
1056 std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1057 if ( PhotometricInterp == "YBR_FULL" )
1061 if ( PhotometricInterp == GDCM_UNFOUND )
1063 gdcmWarningMacro( "Not found : YBR Full (0028,0004)");
1069 * \brief tells us if LUT are used
1070 * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1071 * are NOT considered as LUT, since nobody knows
1072 * how to deal with them
1073 * Please warn me if you know sbdy that *does* know ... jprx
1074 * @return true if LUT Descriptors and LUT Tables were found
1078 // Check the presence of the LUT Descriptors, and LUT Tables
1080 if ( !GetDocEntry(0x0028,0x1101) )
1084 // LutDescriptorGreen
1085 if ( !GetDocEntry(0x0028,0x1102) )
1089 // LutDescriptorBlue
1090 if ( !GetDocEntry(0x0028,0x1103) )
1094 // Red Palette Color Lookup Table Data
1095 if ( !GetDocEntry(0x0028,0x1201) )
1099 // Green Palette Color Lookup Table Data
1100 if ( !GetDocEntry(0x0028,0x1202) )
1104 // Blue Palette Color Lookup Table Data
1105 if ( !GetDocEntry(0x0028,0x1203) )
1110 // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1111 // NOT taken into account, but we don't know how to use it ...
1116 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1118 * @return Lookup Table number of Bits , 0 by default
1119 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1120 * @ return bit number of each LUT item
1122 int File::GetLUTNbits()
1124 std::vector<std::string> tokens;
1127 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1128 // = Lookup Table Desc-Blue
1129 // Consistency already checked in GetLUTLength
1130 std::string lutDescription = GetEntryValue(0x0028,0x1101);
1131 if ( lutDescription == GDCM_UNFOUND )
1136 tokens.clear(); // clean any previous value
1137 Util::Tokenize ( lutDescription, tokens, "\\" );
1138 //LutLength=atoi(tokens[0].c_str());
1139 //LutDepth=atoi(tokens[1].c_str());
1141 lutNbits = atoi( tokens[2].c_str() );
1148 *\brief gets the info from 0028,1052 : Rescale Intercept
1149 * @return Rescale Intercept
1151 float File::GetRescaleIntercept()
1153 float resInter = 0.;
1154 /// 0028 1052 DS IMG Rescale Intercept
1155 const std::string &strRescInter = GetEntryValue(0x0028,0x1052);
1156 if ( strRescInter != GDCM_UNFOUND )
1158 if ( sscanf( strRescInter.c_str(), "%f ", &resInter) != 1 )
1160 // bug in the element 0x0028,0x1052
1161 gdcmWarningMacro( "Rescale Intercept (0028,1052) is empty." );
1169 *\brief gets the info from 0028,1053 : Rescale Slope
1170 * @return Rescale Slope
1172 float File::GetRescaleSlope()
1174 float resSlope = 1.;
1175 //0028 1053 DS IMG Rescale Slope
1176 std::string strRescSlope = GetEntryValue(0x0028,0x1053);
1177 if ( strRescSlope != GDCM_UNFOUND )
1179 if ( sscanf( strRescSlope.c_str(), "%f ", &resSlope) != 1 )
1181 // bug in the element 0x0028,0x1053
1182 gdcmWarningMacro( "Rescale Slope (0028,1053) is empty.");
1190 * \brief This function is intended to user who doesn't want
1191 * to have to manage a LUT and expects to get an RBG Pixel image
1192 * (or a monochrome one ...)
1193 * \warning to be used with GetImagePixels()
1194 * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1196 int File::GetNumberOfScalarComponents()
1198 if ( GetSamplesPerPixel() == 3 )
1203 // 0028 0100 US IMG Bits Allocated
1204 // (in order no to be messed up by old RGB images)
1205 if ( GetEntryValue(0x0028,0x0100) == "24" )
1210 std::string strPhotometricInterpretation = GetEntryValue(0x0028,0x0004);
1212 if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1214 if ( HasLUT() )// PALETTE COLOR is NOT enough
1224 // beware of trailing space at end of string
1225 // DICOM tags are never of odd length
1226 if ( strPhotometricInterpretation == GDCM_UNFOUND ||
1227 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1228 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1234 // we assume that *all* kinds of YBR are dealt with
1240 * \brief This function is intended to user that DOESN'T want
1241 * to get RGB pixels image when it's stored as a PALETTE COLOR image
1242 * - the (vtk) user is supposed to know how deal with LUTs -
1243 * \warning to be used with GetImagePixelsRaw()
1244 * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1246 int File::GetNumberOfScalarComponentsRaw()
1248 // 0028 0100 US IMG Bits Allocated
1249 // (in order no to be messed up by old RGB images)
1250 if ( File::GetEntryValue(0x0028,0x0100) == "24" )
1255 // we assume that *all* kinds of YBR are dealt with
1256 return GetSamplesPerPixel();
1260 * \brief Recover the offset (from the beginning of the file)
1261 * of *image* pixels (not *icone image* pixels, if any !)
1262 * @return Pixel Offset
1264 size_t File::GetPixelOffset()
1266 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1269 return pxlElement->GetOffset();
1273 gdcmDebugMacro( "Big trouble : Pixel Element ("
1274 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1280 * \brief Recover the pixel area length (in Bytes)
1281 * @return Pixel Element Length, as stored in the header
1282 * (NOT the memory space necessary to hold the Pixels
1283 * -in case of embeded compressed image-)
1284 * 0 : NOT USABLE file. The caller has to check.
1286 size_t File::GetPixelAreaLength()
1288 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1291 return pxlElement->GetLength();
1295 gdcmDebugMacro( "Big trouble : Pixel Element ("
1296 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1302 * \brief Adds the characteristics of a new element we want to anonymize
1303 * @param group Group number of the target tag.
1304 * @param elem Element number of the target tag.
1305 * @param value new value (string) to substitute with
1307 void File::AddAnonymizeElement (uint16_t group, uint16_t elem,
1308 std::string const &value)
1314 UserAnonymizeList.push_back(el);
1318 * \brief Overwrites in the file the values of the DicomElements
1321 void File::AnonymizeNoLoad()
1323 std::fstream *fp = new std::fstream(Filename.c_str(),
1324 std::ios::in | std::ios::out | std::ios::binary);
1328 uint32_t valLgth = 0;
1329 std::string *spaces;
1330 for (ListElements::iterator it = UserAnonymizeList.begin();
1331 it != UserAnonymizeList.end();
1334 d = GetDocEntry( (*it).Group, (*it).Elem);
1339 if ( dynamic_cast<SeqEntry *>(d) )
1341 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1345 offset = d->GetOffset();
1346 lgth = d->GetLength();
1349 spaces = new std::string( lgth-valLgth, ' ');
1350 (*it).Value = (*it).Value + *spaces;
1353 fp->seekp( offset, std::ios::beg );
1354 fp->write( (*it).Value.c_str(), lgth );
1362 * \brief anonymize a File (remove Patient's personal info passed with
1363 * AddAnonymizeElement()
1364 * \note You cannot Anonymize a BinEntry (to be fixed)
1366 bool File::AnonymizeFile()
1368 // If Anonymisation list is empty, let's perform some basic anonymization
1369 if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1371 // If exist, replace by spaces
1372 SetValEntry (" ",0x0010, 0x2154); // Telephone
1373 SetValEntry (" ",0x0010, 0x1040); // Adress
1374 SetValEntry (" ",0x0010, 0x0020); // Patient ID
1376 DocEntry* patientNameHE = GetDocEntry (0x0010, 0x0010);
1378 if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1380 std::string studyInstanceUID = GetEntryValue (0x0020, 0x000d);
1381 if ( studyInstanceUID != GDCM_UNFOUND )
1383 SetValEntry(studyInstanceUID, 0x0010, 0x0010);
1387 SetValEntry("anonymized", 0x0010, 0x0010);
1394 for (ListElements::iterator it = UserAnonymizeList.begin();
1395 it != UserAnonymizeList.end();
1398 d = GetDocEntry( (*it).Group, (*it).Elem);
1403 if ( dynamic_cast<SeqEntry *>(d) )
1405 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1409 if ( dynamic_cast<BinEntry *>(d) )
1411 gdcmWarningMacro( "To 'Anonymize' a BinEntry, better use AnonymizeNoLoad (FIXME) ");
1415 SetValEntry ((*it).Value, (*it).Group, (*it).Elem);
1419 // In order to make definitively impossible any further identification
1420 // remove or replace all the stuff that contains a Date
1422 //0008 0012 DA ID Instance Creation Date
1423 //0008 0020 DA ID Study Date
1424 //0008 0021 DA ID Series Date
1425 //0008 0022 DA ID Acquisition Date
1426 //0008 0023 DA ID Content Date
1427 //0008 0024 DA ID Overlay Date
1428 //0008 0025 DA ID Curve Date
1429 //0008 002a DT ID Acquisition Datetime
1430 //0018 9074 DT ACQ Frame Acquisition Datetime
1431 //0018 9151 DT ACQ Frame Reference Datetime
1432 //0018 a002 DT ACQ Contribution Date Time
1433 //0020 3403 SH REL Modified Image Date (RET)
1434 //0032 0032 DA SDY Study Verified Date
1435 //0032 0034 DA SDY Study Read Date
1436 //0032 1000 DA SDY Scheduled Study Start Date
1437 //0032 1010 DA SDY Scheduled Study Stop Date
1438 //0032 1040 DA SDY Study Arrival Date
1439 //0032 1050 DA SDY Study Completion Date
1440 //0038 001a DA VIS Scheduled Admission Date
1441 //0038 001c DA VIS Scheduled Discharge Date
1442 //0038 0020 DA VIS Admitting Date
1443 //0038 0030 DA VIS Discharge Date
1444 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1445 //0040 0004 DA PRC Scheduled Procedure Step End Date
1446 //0040 0244 DA PRC Performed Procedure Step Start Date
1447 //0040 0250 DA PRC Performed Procedure Step End Date
1448 //0040 2004 DA PRC Issue Date of Imaging Service Request
1449 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1450 //0040 4011 DT PRC Expected Completion Date and Time
1451 //0040 a030 DT PRC Verification Date Time
1452 //0040 a032 DT PRC Observation Date Time
1453 //0040 a120 DT PRC DateTime
1454 //0040 a121 DA PRC Date
1455 //0040 a13a DT PRC Referenced Datetime
1456 //0070 0082 DA ??? Presentation Creation Date
1457 //0100 0420 DT ??? SOP Autorization Date and Time
1458 //0400 0105 DT ??? Digital Signature DateTime
1459 //2100 0040 DA PJ Creation Date
1460 //3006 0008 DA SSET Structure Set Date
1461 //3008 0024 DA ??? Treatment Control Point Date
1462 //3008 0054 DA ??? First Treatment Date
1463 //3008 0056 DA ??? Most Recent Treatment Date
1464 //3008 0162 DA ??? Safe Position Exit Date
1465 //3008 0166 DA ??? Safe Position Return Date
1466 //3008 0250 DA ??? Treatment Date
1467 //300a 0006 DA RT RT Plan Date
1468 //300a 022c DA RT Air Kerma Rate Reference Date
1469 //300e 0004 DA RT Review Date
1475 * \brief Performs some consistency checking on various 'File related'
1476 * (as opposed to 'DicomDir related') entries
1477 * then writes in a file all the (Dicom Elements) included the Pixels
1478 * @param fileName file name to write to
1479 * @param writetype type of the file to be written
1480 * (ACR, ExplicitVR, ImplicitVR)
1482 bool File::Write(std::string fileName, FileType writetype)
1484 std::ofstream *fp = new std::ofstream(fileName.c_str(),
1485 std::ios::out | std::ios::binary);
1488 gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1492 // Entry : 0002|0000 = group length -> recalculated
1493 ValEntry*e0000 = GetValEntry(0x0002,0x0000);
1496 std::ostringstream sLen;
1497 sLen << ComputeGroup0002Length(writetype);
1498 e0000->SetValue(sLen.str());
1501 int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1504 // no (GrPixel, NumPixel) element
1505 std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1506 s_lgPix = Util::DicomString( s_lgPix.c_str() );
1507 InsertValEntry(s_lgPix,GrPixel, 0x0000);
1510 Document::WriteContent(fp, writetype);
1518 //-----------------------------------------------------------------------------
1522 //-----------------------------------------------------------------------------
1525 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1526 * Compute the RLE extra information and store it in \ref RLEInfo
1527 * for later pixel retrieval usage.
1529 void File::ComputeRLEInfo()
1531 std::string ts = GetTransferSyntax();
1532 if ( !Global::GetTS()->IsRLELossless(ts) )
1537 // Encoded pixel data: for the time being we are only concerned with
1538 // Jpeg or RLE Pixel data encodings.
1539 // As stated in PS 3.5-2003, section 8.2 p44:
1540 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1541 // value representation OB is used".
1542 // Hence we expect an OB value representation. Concerning OB VR,
1543 // the section PS 3.5-2003, section A.4.c p 58-59, states:
1544 // "For the Value Representations OB and OW, the encoding shall meet the
1545 // following specifications depending on the Data element tag:"
1547 // - the first item in the sequence of items before the encoded pixel
1548 // data stream shall be basic offset table item. The basic offset table
1549 // item value, however, is not required to be present"
1550 ReadAndSkipEncapsulatedBasicOffsetTable();
1552 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1553 // Loop on the individual frame[s] and store the information
1554 // on the RLE fragments in a RLEFramesInfo.
1555 // Note: - when only a single frame is present, this is a
1557 // - when more than one frame are present, then we are in
1558 // the case of a multi-frame image.
1560 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1562 // Parse the RLE Header and store the corresponding RLE Segment
1563 // Offset Table information on fragments of this current Frame.
1564 // Note that the fragment pixels themselves are not loaded
1565 // (but just skipped).
1566 long frameOffset = Fp->tellg();
1568 uint32_t nbRleSegments = ReadInt32();
1569 if ( nbRleSegments > 16 )
1571 // There should be at most 15 segments (refer to RLEFrame class)
1572 gdcmWarningMacro( "Too many segments.");
1575 uint32_t rleSegmentOffsetTable[16];
1576 for( int k = 1; k <= 15; k++ )
1578 rleSegmentOffsetTable[k] = ReadInt32();
1581 // Deduce from both RLE Header and frameLength
1582 // the fragment length, and again store this info
1583 // in a RLEFramesInfo.
1584 long rleSegmentLength[15];
1585 // skipping (not reading) RLE Segments
1586 if ( nbRleSegments > 1)
1588 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1590 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
1591 - rleSegmentOffsetTable[k];
1592 SkipBytes(rleSegmentLength[k]);
1596 rleSegmentLength[nbRleSegments] = frameLength
1597 - rleSegmentOffsetTable[nbRleSegments];
1598 SkipBytes(rleSegmentLength[nbRleSegments]);
1600 // Store the collected info
1601 RLEFrame *newFrame = new RLEFrame;
1602 newFrame->SetNumberOfFragments(nbRleSegments);
1603 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1605 newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1606 newFrame->SetLength(uk,rleSegmentLength[uk]);
1608 RLEInfo->AddFrame(newFrame);
1611 // Make sure that we encounter a 'Sequence Delimiter Item'
1612 // at the end of the item :
1613 if ( !ReadTag(0xfffe, 0xe0dd) )
1615 gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1620 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1621 * Compute the jpeg extra information (fragment[s] offset[s] and
1622 * length) and store it[them] in \ref JPEGInfo for later pixel
1625 void File::ComputeJPEGFragmentInfo()
1627 // If you need to, look for comments of ComputeRLEInfo().
1628 std::string ts = GetTransferSyntax();
1629 if ( ! Global::GetTS()->IsJPEG(ts) )
1634 ReadAndSkipEncapsulatedBasicOffsetTable();
1636 // Loop on the fragments[s] and store the parsed information in a
1638 long fragmentLength;
1639 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1641 long fragmentOffset = Fp->tellg();
1643 // Store the collected info
1644 JPEGFragment *newFragment = new JPEGFragment;
1645 newFragment->SetOffset(fragmentOffset);
1646 newFragment->SetLength(fragmentLength);
1647 JPEGInfo->AddFragment(newFragment);
1649 SkipBytes(fragmentLength);
1652 // Make sure that we encounter a 'Sequence Delimiter Item'
1653 // at the end of the item :
1654 if ( !ReadTag(0xfffe, 0xe0dd) )
1656 gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1661 * \brief Assuming the internal file pointer \ref Document::Fp
1662 * is placed at the beginning of a tag check whether this
1663 * tag is (TestGroup, TestElem).
1664 * \warning On success the internal file pointer \ref Document::Fp
1665 * is modified to point after the tag.
1666 * On failure (i.e. when the tag wasn't the expected tag
1667 * (TestGroup, TestElem) the internal file pointer
1668 * \ref Document::Fp is restored to it's original position.
1669 * @param testGroup The expected group of the tag.
1670 * @param testElem The expected Element of the tag.
1671 * @return True on success, false otherwise.
1673 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1675 long positionOnEntry = Fp->tellg();
1676 long currentPosition = Fp->tellg(); // On debugging purposes
1678 // Read the Item Tag group and element, and make
1679 // sure they are what we expected:
1680 uint16_t itemTagGroup;
1681 uint16_t itemTagElem;
1684 itemTagGroup = ReadInt16();
1685 itemTagElem = ReadInt16();
1687 catch ( FormatError e )
1689 //std::cerr << e << std::endl;
1692 if ( itemTagGroup != testGroup || itemTagElem != testElem )
1694 gdcmWarningMacro( "Wrong Item Tag found:"
1695 << " We should have found tag ("
1696 << std::hex << testGroup << "," << testElem << ")" << std::endl
1697 << " but instead we encountered tag ("
1698 << std::hex << itemTagGroup << "," << itemTagElem << ")"
1699 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
1701 Fp->seekg(positionOnEntry, std::ios::beg);
1709 * \brief Assuming the internal file pointer \ref Document::Fp
1710 * is placed at the beginning of a tag (TestGroup, TestElement),
1711 * read the length associated to the Tag.
1712 * \warning On success the internal file pointer \ref Document::Fp
1713 * is modified to point after the tag and it's length.
1714 * On failure (i.e. when the tag wasn't the expected tag
1715 * (TestGroup, TestElement) the internal file pointer
1716 * \ref Document::Fp is restored to it's original position.
1717 * @param testGroup The expected Group of the tag.
1718 * @param testElem The expected Element of the tag.
1719 * @return On success returns the length associated to the tag. On failure
1722 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1725 if ( !ReadTag(testGroup, testElem) )
1730 //// Then read the associated Item Length
1731 long currentPosition = Fp->tellg();
1732 uint32_t itemLength = ReadInt32();
1734 gdcmWarningMacro( "Basic Item Length is: "
1735 << itemLength << std::endl
1736 << " at address: " << std::hex << (unsigned int)currentPosition);
1742 * \brief When parsing the Pixel Data of an encapsulated file, read
1743 * the basic offset table (when present, and BTW dump it).
1745 void File::ReadAndSkipEncapsulatedBasicOffsetTable()
1747 //// Read the Basic Offset Table Item Tag length...
1748 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1750 // When present, read the basic offset table itself.
1751 // Notes: - since the presence of this basic offset table is optional
1752 // we can't rely on it for the implementation, and we will simply
1753 // trash it's content (when present).
1754 // - still, when present, we could add some further checks on the
1755 // lengths, but we won't bother with such fuses for the time being.
1756 if ( itemLength != 0 )
1758 char *basicOffsetTableItemValue = new char[itemLength + 1];
1759 Fp->read(basicOffsetTableItemValue, itemLength);
1762 for (unsigned int i=0; i < itemLength; i += 4 )
1764 uint32_t individualLength = str2num( &basicOffsetTableItemValue[i],
1766 gdcmWarningMacro( "Read one length: " <<
1767 std::hex << individualLength );
1771 delete[] basicOffsetTableItemValue;
1775 // These are the deprecated method that one day should be removed (after the next release)
1777 #ifndef GDCM_LEGACY_REMOVE
1779 * \brief Constructor (DEPRECATED : temporaryly kept not to break the API)
1780 * @param filename name of the file whose header we want to analyze
1781 * @deprecated do not use any longer
1783 File::File( std::string const &filename )
1786 RLEInfo = new RLEFramesInfo;
1787 JPEGInfo = new JPEGFragmentsInfo;
1789 SetFileName( filename );
1790 Load( ); // gdcm::Document is first Loaded, then the 'File part'
1794 * \brief Loader. (DEPRECATED : temporaryly kept not to break the API)
1795 * @param fileName file to be open for parsing
1796 * @return false if file cannot be open or no swap info was found,
1797 * or no tag was found.
1798 * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
1800 bool File::Load( std::string const &fileName )
1802 GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
1804 SetFileName( fileName );
1805 if ( ! this->Document::Load( ) )
1808 return DoTheLoadingJob( );
1812 //-----------------------------------------------------------------------------
1815 //-----------------------------------------------------------------------------
1816 } // end namespace gdcm