1 /*=========================================================================
4 Module: $RCSfile: gdcmFile.cxx,v $
6 Date: $Date: 2005/10/10 22:25:05 $
7 Version: $Revision: 1.274 $
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
121 BasicOffsetTableItemValue = 0;
126 * \brief Canonical destructor.
134 delete[] BasicOffsetTableItemValue;
137 //-----------------------------------------------------------------------------
141 * @return false if file cannot be open or no swap info was found,
142 * or no tag was found.
146 if ( ! this->Document::Load( ) )
149 return DoTheLoadingJob( );
153 * \brief Does the Loading Job (internal use only)
154 * @return false if file cannot be open or no swap info was found,
155 * or no tag was found.
157 bool File::DoTheLoadingJob( )
160 // for some ACR-NEMA images GrPixel, NumPixel is *not* 7fe0,0010
161 // We may encounter the 'RETired' (0x0028, 0x0200) tag
162 // (Image Location") . This entry contains the number of
163 // the group that contains the pixel data (hence the "Pixel Data"
164 // is found by indirection through the "Image Location").
165 // Inside the group pointed by "Image Location" the searched element
166 // is conventionally the element 0x0010 (when the norm is respected).
167 // When the "Image Location" is missing we default to group 0x7fe0.
168 // Note: this IS the right place for the code
171 const std::string &imgLocation = GetEntryValue(0x0028, 0x0200);
172 if ( imgLocation == GDCM_UNFOUND )
179 GrPixel = (uint16_t) atoi( imgLocation.c_str() );
182 // sometimes Image Location value doesn't follow
183 // the supposed processor endianness.
184 // see gdcmData/cr172241.dcm
185 if ( GrPixel == 0xe07f )
190 if ( GrPixel != 0x7fe0 )
192 // This is a kludge for old dirty Philips imager.
200 // Now, we know GrPixel and NumPixel.
201 // Let's create a VirtualDictEntry to allow a further VR modification
202 // and force VR to match with BitsAllocated.
203 DocEntry *entry = GetDocEntry(GrPixel, NumPixel);
206 // Compute the RLE or JPEG info
208 const std::string &ts = GetTransferSyntax();
209 Fp->seekg( entry->GetOffset(), std::ios::beg );
210 if ( Global::GetTS()->IsRLELossless(ts) )
212 else if ( Global::GetTS()->IsJPEG(ts) )
213 ComputeJPEGFragmentInfo();
216 // Create a new BinEntry to change the DictEntry
217 // The changed DictEntry will have
218 // - a correct PixelVR OB or OW)
219 // - the name to "Pixel Data"
220 BinEntry *oldEntry = dynamic_cast<BinEntry *>(entry);
224 // 8 bits allocated is a 'O Bytes' , as well as 24 (old ACR-NEMA RGB)
225 // more than 8 (i.e 12, 16) is a 'O Words'
226 if ( GetBitsAllocated() == 8 || GetBitsAllocated() == 24 )
231 // Change only made if usefull
232 if ( PixelVR != oldEntry->GetVR() )
234 DictEntry* newDict = NewVirtualDictEntry(GrPixel,NumPixel,
235 PixelVR,"1","Pixel Data");
237 BinEntry *newEntry = new BinEntry(newDict);
238 newEntry->Copy(entry);
239 newEntry->SetBinArea(oldEntry->GetBinArea(),oldEntry->IsSelfArea());
240 oldEntry->SetSelfArea(false);
242 RemoveEntry(oldEntry);
250 * \brief This predicate, based on hopefully reasonable heuristics,
251 * decides whether or not the current File was properly parsed
252 * and contains the mandatory information for being considered as
253 * a well formed and usable Dicom/Acr File.
254 * @return true when File is the one of a reasonable Dicom/Acr file,
257 bool File::IsReadable()
259 if ( !Document::IsReadable() )
264 const std::string &res = GetEntryValue(0x0028, 0x0005);
265 if ( res != GDCM_UNFOUND && atoi(res.c_str()) > 4 )
267 gdcmWarningMacro("Wrong Image Dimensions" << res);
268 return false; // Image Dimensions
270 bool b0028_0100 = true;
271 if ( !GetDocEntry(0x0028, 0x0100) )
273 gdcmWarningMacro("Bits Allocated (0028|0100) not found");
274 //return false; // "Bits Allocated"
277 bool b0028_0101 = true;
278 if ( !GetDocEntry(0x0028, 0x0101) )
280 gdcmWarningMacro("Bits Stored (0028|0101) not found");
281 //return false; // "Bits Stored"
284 bool b0028_0102 = true;
285 if ( !GetDocEntry(0x0028, 0x0102) )
287 gdcmWarningMacro("Hight Bit (0028|0102) not found");
288 //return false; // "High Bit"
291 bool b0028_0103 = true;
292 if ( !GetDocEntry(0x0028, 0x0103) )
294 gdcmWarningMacro("Pixel Representation (0028|0103) not found");
295 //return false; // "Pixel Representation" i.e. 'Sign' ( 0 : unsigned, 1 : signed)
299 if ( !b0028_0100 && !b0028_0101 && !b0028_0102 && !b0028_0103)
301 gdcmWarningMacro("Too much mandatory Tags missing !");
305 if ( !GetDocEntry(GrPixel, NumPixel) )
307 gdcmWarningMacro("Pixel Dicom Element " << std::hex <<
308 GrPixel << "|" << NumPixel << "not found");
309 return false; // Pixel Dicom Element not found :-(
315 * \brief gets the info from 0020,0013 : Image Number else 0.
316 * @return image number
318 int File::GetImageNumber()
320 //0020 0013 : Image Number
321 std::string strImNumber = GetEntryValue(0x0020,0x0013);
322 if ( strImNumber != GDCM_UNFOUND )
324 return atoi( strImNumber.c_str() );
330 * \brief gets the info from 0008,0060 : Modality
331 * @return Modality Type
333 ModalityType File::GetModality()
335 // 0008 0060 : Modality
336 std::string strModality = GetEntryValue(0x0008,0x0060);
337 if ( strModality != GDCM_UNFOUND )
339 if ( strModality.find("AU") < strModality.length()) return AU;
340 else if ( strModality.find("AS") < strModality.length()) return AS;
341 else if ( strModality.find("BI") < strModality.length()) return BI;
342 else if ( strModality.find("CF") < strModality.length()) return CF;
343 else if ( strModality.find("CP") < strModality.length()) return CP;
344 else if ( strModality.find("CR") < strModality.length()) return CR;
345 else if ( strModality.find("CT") < strModality.length()) return CT;
346 else if ( strModality.find("CS") < strModality.length()) return CS;
347 else if ( strModality.find("DD") < strModality.length()) return DD;
348 else if ( strModality.find("DF") < strModality.length()) return DF;
349 else if ( strModality.find("DG") < strModality.length()) return DG;
350 else if ( strModality.find("DM") < strModality.length()) return DM;
351 else if ( strModality.find("DS") < strModality.length()) return DS;
352 else if ( strModality.find("DX") < strModality.length()) return DX;
353 else if ( strModality.find("ECG") < strModality.length()) return ECG;
354 else if ( strModality.find("EPS") < strModality.length()) return EPS;
355 else if ( strModality.find("FA") < strModality.length()) return FA;
356 else if ( strModality.find("FS") < strModality.length()) return FS;
357 else if ( strModality.find("HC") < strModality.length()) return HC;
358 else if ( strModality.find("HD") < strModality.length()) return HD;
359 else if ( strModality.find("LP") < strModality.length()) return LP;
360 else if ( strModality.find("LS") < strModality.length()) return LS;
361 else if ( strModality.find("MA") < strModality.length()) return MA;
362 else if ( strModality.find("MR") < strModality.length()) return MR;
363 else if ( strModality.find("NM") < strModality.length()) return NM;
364 else if ( strModality.find("OT") < strModality.length()) return OT;
365 else if ( strModality.find("PT") < strModality.length()) return PT;
366 else if ( strModality.find("RF") < strModality.length()) return RF;
367 else if ( strModality.find("RG") < strModality.length()) return RG;
368 else if ( strModality.find("RTDOSE")
369 < strModality.length()) return RTDOSE;
370 else if ( strModality.find("RTIMAGE")
371 < strModality.length()) return RTIMAGE;
372 else if ( strModality.find("RTPLAN")
373 < strModality.length()) return RTPLAN;
374 else if ( strModality.find("RTSTRUCT")
375 < strModality.length()) return RTSTRUCT;
376 else if ( strModality.find("SM") < strModality.length()) return SM;
377 else if ( strModality.find("ST") < strModality.length()) return ST;
378 else if ( strModality.find("TG") < strModality.length()) return TG;
379 else if ( strModality.find("US") < strModality.length()) return US;
380 else if ( strModality.find("VF") < strModality.length()) return VF;
381 else if ( strModality.find("XA") < strModality.length()) return XA;
382 else if ( strModality.find("XC") < strModality.length()) return XC;
386 /// \todo throw error return value ???
387 /// specified <> unknown in our database
395 * \brief Retrieve the number of columns of image.
396 * @return The encountered size when found, 0 by default.
397 * 0 means the file is NOT USABLE. The caller will have to check
401 const std::string &strSize = GetEntryValue(0x0028,0x0011);
402 if ( strSize == GDCM_UNFOUND )
406 return atoi( strSize.c_str() );
410 * \brief Retrieve the number of lines of image.
411 * \warning The defaulted value is 1 as opposed to File::GetXSize()
412 * @return The encountered size when found, 1 by default
413 * (The ACR-NEMA file contains a Signal, not an Image).
417 const std::string &strSize = GetEntryValue(0x0028,0x0010);
418 if ( strSize != GDCM_UNFOUND )
420 return atoi( strSize.c_str() );
427 // The Rows (0028,0010) entry was optional for ACR/NEMA.
428 // (at least some images didn't have it.)
429 // It might hence be a signal (1D image). So we default to 1:
434 * \brief Retrieve the number of planes of volume or the number
435 * of frames of a multiframe.
436 * \warning When present we consider the "Number of Frames" as the third
437 * dimension. When missing we consider the third dimension as
438 * being the ACR-NEMA "Planes" tag content.
439 * @return The encountered size when found, 1 by default (single image).
443 // Both DicomV3 and ACR/Nema consider the "Number of Frames"
444 // as the third dimension.
445 const std::string &strSize = GetEntryValue(0x0028,0x0008);
446 if ( strSize != GDCM_UNFOUND )
448 return atoi( strSize.c_str() );
451 // We then consider the "Planes" entry as the third dimension
452 const std::string &strSize2 = GetEntryValue(0x0028,0x0012);
453 if ( strSize2 != GDCM_UNFOUND )
455 return atoi( strSize2.c_str() );
461 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
462 * then 0028,0030 : Pixel Spacing
464 * @return X dimension of a pixel
466 float File::GetXSpacing()
468 float xspacing = 1.0;
469 float yspacing = 1.0;
472 // To follow David Clunie's advice, we first check ImagerPixelSpacing
474 const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
475 if ( strImagerPixelSpacing != GDCM_UNFOUND )
477 if ( ( nbValues = sscanf( strImagerPixelSpacing.c_str(),
478 "%f\\%f", &yspacing, &xspacing)) != 2 )
480 // if no values, xspacing is set to 1.0
483 // if single value is found, xspacing is defaulted to yspacing
487 if ( xspacing == 0.0 )
494 const std::string &strSpacing = GetEntryValue(0x0028,0x0030);
496 if ( strSpacing == GDCM_UNFOUND )
498 gdcmWarningMacro( "Unfound Pixel Spacing (0028,0030)" );
502 if ( ( nbValues = sscanf( strSpacing.c_str(),
503 "%f \\%f ", &yspacing, &xspacing)) != 2 )
505 // if no values, xspacing is set to 1.0
508 // if single value is found, xspacing is defaulted to yspacing
512 if ( xspacing == 0.0 )
518 // to avoid troubles with David Clunie's-like images (at least one)
519 if ( xspacing == 0. && yspacing == 0.)
524 gdcmWarningMacro("gdcmData/CT-MONO2-8-abdo.dcm-like problem");
525 // seems to be a bug in the header ...
526 nbValues = sscanf( strSpacing.c_str(), "%f \\0\\%f ", &yspacing, &xspacing);
527 gdcmAssertMacro( nbValues == 2 );
534 * \brief gets the info from 0018,1164 : ImagerPixelSpacing
535 * then from 0028,0030 : Pixel Spacing
537 * @return Y dimension of a pixel
539 float File::GetYSpacing()
543 // To follow David Clunie's advice, we first check ImagerPixelSpacing
545 const std::string &strImagerPixelSpacing = GetEntryValue(0x0018,0x1164);
546 if ( strImagerPixelSpacing != GDCM_UNFOUND )
548 nbValues = sscanf( strImagerPixelSpacing.c_str(), "%f", &yspacing);
550 // if sscanf cannot read any float value, it won't affect yspacing
554 if ( yspacing == 0.0 )
560 std::string strSpacing = GetEntryValue(0x0028,0x0030);
561 if ( strSpacing == GDCM_UNFOUND )
563 gdcmWarningMacro("Unfound Pixel Spacing (0028,0030)");
567 // if sscanf cannot read any float value, it won't affect yspacing
568 nbValues = sscanf( strSpacing.c_str(), "%f", &yspacing);
570 // if no values, yspacing is set to 1.0
574 if ( yspacing == 0.0 )
581 * \brief gets the info from 0018,0088 : Space Between Slices
582 * else from 0018,0050 : Slice Thickness
584 * @return Z dimension of a voxel-to be
586 float File::GetZSpacing()
588 // Spacing Between Slices : distance between the middle of 2 slices
590 // jointives (Spacing between Slices = Slice Thickness)
591 // overlapping (Spacing between Slices < Slice Thickness)
592 // disjointes (Spacing between Slices > Slice Thickness)
593 // Slice Thickness : epaisseur de tissus sur laquelle est acquis le signal
594 // It only concerns the MRI guys, not people wanting to visualize volumes
595 // If Spacing Between Slices is missing,
596 // we suppose slices joint together
598 const std::string &strSpacingBSlices = GetEntryValue(0x0018,0x0088);
600 if ( strSpacingBSlices == GDCM_UNFOUND )
602 gdcmWarningMacro("Unfound Spacing Between Slices (0018,0088)");
603 const std::string &strSliceThickness = GetEntryValue(0x0018,0x0050);
604 if ( strSliceThickness == GDCM_UNFOUND )
606 gdcmWarningMacro("Unfound Slice Thickness (0018,0050)");
611 // if no 'Spacing Between Slices' is found,
612 // we assume slices join together
613 // (no overlapping, no interslice gap)
614 // if they don't, we're fucked up
615 return (float)atof( strSliceThickness.c_str() );
619 return (float)atof( strSpacingBSlices.c_str() );
623 * \brief gets the info from 0020,0032 : Image Position Patient
624 * else from 0020,0030 : Image Position (RET)
626 * @return up-left image corner X position
628 float File::GetXOrigin()
630 float xImPos, yImPos, zImPos;
631 std::string strImPos = GetEntryValue(0x0020,0x0032);
633 if ( strImPos == GDCM_UNFOUND )
635 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
636 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
637 if ( strImPos == GDCM_UNFOUND )
639 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
644 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
653 * \brief gets the info from 0020,0032 : Image Position Patient
654 * else from 0020,0030 : Image Position (RET)
656 * @return up-left image corner Y position
658 float File::GetYOrigin()
660 float xImPos, yImPos, zImPos;
661 std::string strImPos = GetEntryValue(0x0020,0x0032);
663 if ( strImPos == GDCM_UNFOUND)
665 gdcmWarningMacro( "Unfound Image Position Patient (0020,0032)");
666 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
667 if ( strImPos == GDCM_UNFOUND )
669 gdcmWarningMacro( "Unfound Image Position (RET) (0020,0030)");
674 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3 )
683 * \brief gets the info from 0020,0032 : Image Position Patient
684 * else from 0020,0030 : Image Position (RET)
685 * else from 0020,1041 : Slice Location
686 * else from 0020,0050 : Location
688 * @return up-left image corner Z position
690 float File::GetZOrigin()
692 float xImPos, yImPos, zImPos;
693 std::string strImPos = GetEntryValue(0x0020,0x0032);
695 if ( strImPos != GDCM_UNFOUND )
697 if ( sscanf( strImPos.c_str(), "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos) != 3)
699 gdcmWarningMacro( "Wrong Image Position Patient (0020,0032)");
700 return 0.; // bug in the element 0x0020,0x0032
708 strImPos = GetEntryValue(0x0020,0x0030); // For ACR-NEMA images
709 if ( strImPos != GDCM_UNFOUND )
711 if ( sscanf( strImPos.c_str(),
712 "%f \\%f \\%f ", &xImPos, &yImPos, &zImPos ) != 3 )
714 gdcmWarningMacro( "Wrong Image Position (RET) (0020,0030)");
715 return 0.; // bug in the element 0x0020,0x0032
723 // for *very* old ACR-NEMA images
724 std::string strSliceLocation = GetEntryValue(0x0020,0x1041);
725 if ( strSliceLocation != GDCM_UNFOUND )
727 if ( sscanf( strSliceLocation.c_str(), "%f ", &zImPos) != 1)
729 gdcmWarningMacro( "Wrong Slice Location (0020,1041)");
730 return 0.; // bug in the element 0x0020,0x1041
737 gdcmWarningMacro( "Unfound Slice Location (0020,1041)");
739 std::string strLocation = GetEntryValue(0x0020,0x0050);
740 if ( strLocation != GDCM_UNFOUND )
742 if ( sscanf( strLocation.c_str(), "%f ", &zImPos) != 1 )
744 gdcmWarningMacro( "Wrong Location (0020,0050)");
745 return 0.; // bug in the element 0x0020,0x0050
752 gdcmWarningMacro( "Unfound Location (0020,0050)");
754 return 0.; // Hopeless
758 * \brief gets the info from 0020,0037 : Image Orientation Patient
759 * or from 0020 0035 : Image Orientation (RET)
760 * (needed to organize DICOM files based on their x,y,z position)
761 * @param iop adress of the (6)float array to receive values
762 * @return true when one of the tag is found
763 * false when nothing is found
765 bool File::GetImageOrientationPatient( float iop[6] )
767 std::string strImOriPat;
768 //iop is supposed to be float[6]
769 iop[0] = iop[1] = iop[2] = iop[3] = iop[4] = iop[5] = 0.;
771 // 0020 0037 DS REL Image Orientation (Patient)
772 if ( (strImOriPat = GetEntryValue(0x0020,0x0037)) != GDCM_UNFOUND )
774 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
775 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
777 gdcmWarningMacro( "Wrong Image Orientation Patient (0020,0037)."
778 << " Less than 6 values were found." );
783 // 0020 0035 DS REL Image Orientation (RET)
784 else if ( (strImOriPat = GetEntryValue(0x0020,0x0035)) != GDCM_UNFOUND )
786 if ( sscanf( strImOriPat.c_str(), "%f \\ %f \\%f \\%f \\%f \\%f ",
787 &iop[0], &iop[1], &iop[2], &iop[3], &iop[4], &iop[5]) != 6 )
789 gdcmWarningMacro( "wrong Image Orientation Patient (0020,0035). "
790 << "Less than 6 values were found." );
800 * \brief Retrieve the number of Bits Stored (actually used)
801 * (as opposed to number of Bits Allocated)
802 * @return The encountered number of Bits Stored, 0 by default.
803 * 0 means the file is NOT USABLE. The caller has to check it !
805 int File::GetBitsStored()
807 std::string strSize = GetEntryValue( 0x0028, 0x0101 );
808 if ( strSize == GDCM_UNFOUND )
810 gdcmWarningMacro("(0028,0101) is supposed to be mandatory");
811 return 0; // It's supposed to be mandatory
812 // the caller will have to check
814 return atoi( strSize.c_str() );
818 * \brief Retrieve the number of Bits Allocated
819 * (8, 12 -compacted ACR-NEMA files-, 16, 24 -old RGB ACR-NEMA files-,)
820 * @return The encountered Number of Bits Allocated, 0 by default.
821 * 0 means the file is NOT USABLE. The caller has to check it !
823 int File::GetBitsAllocated()
825 std::string strSize = GetEntryValue(0x0028,0x0100);
826 if ( strSize == GDCM_UNFOUND )
828 gdcmWarningMacro( "(0028,0100) is supposed to be mandatory");
829 return 0; // It's supposed to be mandatory
830 // the caller will have to check
832 return atoi( strSize.c_str() );
836 * \brief Retrieve the high bit position.
837 * \warning The method defaults to 0 when information is missing.
838 * The responsability of checking this value is left to the caller.
839 * @return The high bit position when present. 0 when missing.
841 int File::GetHighBitPosition()
843 std::string strSize = GetEntryValue( 0x0028, 0x0102 );
844 if ( strSize == GDCM_UNFOUND )
846 gdcmWarningMacro( "(0028,0102) is supposed to be mandatory");
849 return atoi( strSize.c_str() );
853 * \brief Retrieve the number of Samples Per Pixel
854 * (1 : gray level, 3 : RGB/YBR -1 or 3 Planes-)
855 * @return The encountered number of Samples Per Pixel, 1 by default.
856 * (we assume Gray level Pixels)
858 int File::GetSamplesPerPixel()
860 const std::string &strSize = GetEntryValue(0x0028,0x0002);
861 if ( strSize == GDCM_UNFOUND )
863 gdcmWarningMacro( "(0028,0002) is supposed to be mandatory");
864 return 1; // Well, it's supposed to be mandatory ...
865 // but sometimes it's missing : *we* assume Gray pixels
867 return atoi( strSize.c_str() );
871 * \brief Retrieve the Planar Configuration for RGB images
872 * (0 : RGB Pixels , 1 : R Plane + G Plane + B Plane)
873 * @return The encountered Planar Configuration, 0 by default.
875 int File::GetPlanarConfiguration()
877 std::string strSize = GetEntryValue(0x0028,0x0006);
878 if ( strSize == GDCM_UNFOUND )
880 gdcmWarningMacro( "Not found : Planar Configuration (0028,0006)");
883 return atoi( strSize.c_str() );
887 * \brief Return the size (in bytes) of a single pixel of data.
888 * @return The size in bytes of a single pixel of data; 0 by default
889 * 0 means the file is NOT USABLE; the caller will have to check
891 int File::GetPixelSize()
893 // 0028 0100 US IMG Bits Allocated
894 // (in order no to be messed up by old ACR-NEMA RGB images)
895 // if (File::GetEntryValue(0x0028,0x0100) == "24")
897 assert( !(GetEntryValue(0x0028,0x0100) == "24") );
899 std::string pixelType = GetPixelType();
900 if ( pixelType == "8U" || pixelType == "8S" )
904 if ( pixelType == "16U" || pixelType == "16S")
908 if ( pixelType == "32U" || pixelType == "32S")
912 if ( pixelType == "FD" )
916 gdcmWarningMacro( "Unknown pixel type");
921 * \brief Build the Pixel Type of the image.
922 * Possible values are:
923 * - 8U unsigned 8 bit,
925 * - 16U unsigned 16 bit,
926 * - 16S signed 16 bit,
927 * - 32U unsigned 32 bit,
928 * - 32S signed 32 bit,
929 * - FD floating double 64 bits (Not kosher DICOM, but so usefull!)
930 * \warning 12 bit images appear as 16 bit.
931 * 24 bit images appear as 8 bit + photochromatic interp ="RGB "
932 * + Planar Configuration = 0
933 * @return 0S if nothing found. NOT USABLE file. The caller has to check
935 std::string File::GetPixelType()
937 std::string bitsAlloc = GetEntryValue(0x0028, 0x0100); // Bits Allocated
938 if ( bitsAlloc == GDCM_UNFOUND )
940 gdcmWarningMacro( "Missing Bits Allocated (0028,0100)");
941 bitsAlloc = "16"; // default and arbitrary value, not to polute the output
944 if ( bitsAlloc == "64" )
948 else if ( bitsAlloc == "12" )
950 // It will be unpacked
953 else if ( bitsAlloc == "24" )
955 // (in order no to be messed up by old RGB images)
959 std::string sign = GetEntryValue(0x0028, 0x0103);//"Pixel Representation"
961 if (sign == GDCM_UNFOUND )
963 gdcmWarningMacro( "Missing Pixel Representation (0028,0103)");
964 sign = "U"; // default and arbitrary value, not to polute the output
966 else if ( sign == "0" )
974 return bitsAlloc + sign;
978 * \brief Check whether the pixels are signed (1) or UNsigned (0) data.
979 * \warning The method defaults to false (UNsigned) when tag 0028|0103
981 * The responsability of checking this value is left to the caller
982 * (NO transformation is performed on the pixels to make then >0)
983 * @return True when signed, false when UNsigned
985 bool File::IsSignedPixelData()
987 std::string strSign = GetEntryValue( 0x0028, 0x0103 );
988 if ( strSign == GDCM_UNFOUND )
990 gdcmWarningMacro( "(0028,0103) is supposed to be mandatory");
993 int sign = atoi( strSign.c_str() );
1002 * \brief Check whether this a monochrome picture (gray levels) or not,
1003 * using "Photometric Interpretation" tag (0x0028,0x0004).
1004 * @return true when "MONOCHROME1" or "MONOCHROME2". False otherwise.
1006 bool File::IsMonochrome()
1008 const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1009 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1")
1010 || Util::DicomStringEqual(PhotometricInterp, "MONOCHROME2") )
1014 if ( PhotometricInterp == GDCM_UNFOUND )
1016 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1022 * \brief Check whether this a MONOCHROME1 picture (high values = dark)
1023 * or not using "Photometric Interpretation" tag (0x0028,0x0004).
1024 * @return true when "MONOCHROME1" . False otherwise.
1026 bool File::IsMonochrome1()
1028 const std::string &PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1029 if ( Util::DicomStringEqual(PhotometricInterp, "MONOCHROME1") )
1033 if ( PhotometricInterp == GDCM_UNFOUND )
1035 gdcmWarningMacro( "Not found : Photometric Interpretation (0028,0004)");
1041 * \brief Check whether this a "PALETTE COLOR" picture or not by accessing
1042 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1043 * @return true when "PALETTE COLOR". False otherwise.
1045 bool File::IsPaletteColor()
1047 std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1048 if ( PhotometricInterp == "PALETTE COLOR " )
1052 if ( PhotometricInterp == GDCM_UNFOUND )
1054 gdcmWarningMacro( "Not found : Palette color (0028,0004)");
1060 * \brief Check whether this a "YBR_FULL" color picture or not by accessing
1061 * the "Photometric Interpretation" tag ( 0x0028, 0x0004 ).
1062 * @return true when "YBR_FULL". False otherwise.
1064 bool File::IsYBRFull()
1066 std::string PhotometricInterp = GetEntryValue( 0x0028, 0x0004 );
1067 if ( PhotometricInterp == "YBR_FULL" )
1071 if ( PhotometricInterp == GDCM_UNFOUND )
1073 gdcmWarningMacro( "Not found : YBR Full (0028,0004)");
1079 * \brief tells us if LUT are used
1080 * \warning Right now, 'Segmented xxx Palette Color Lookup Table Data'
1081 * are NOT considered as LUT, since nobody knows
1082 * how to deal with them
1083 * Please warn me if you know sbdy that *does* know ... jprx
1084 * @return true if LUT Descriptors and LUT Tables were found
1088 // Check the presence of the LUT Descriptors, and LUT Tables
1090 if ( !GetDocEntry(0x0028,0x1101) )
1094 // LutDescriptorGreen
1095 if ( !GetDocEntry(0x0028,0x1102) )
1099 // LutDescriptorBlue
1100 if ( !GetDocEntry(0x0028,0x1103) )
1104 // Red Palette Color Lookup Table Data
1105 if ( !GetDocEntry(0x0028,0x1201) )
1109 // Green Palette Color Lookup Table Data
1110 if ( !GetDocEntry(0x0028,0x1202) )
1114 // Blue Palette Color Lookup Table Data
1115 if ( !GetDocEntry(0x0028,0x1203) )
1120 // FIXME : (0x0028,0x3006) : LUT Data (CTX dependent)
1121 // NOT taken into account, but we don't know how to use it ...
1126 * \brief gets the info from 0028,1101 : Lookup Table Desc-Red
1128 * @return Lookup Table number of Bits , 0 by default
1129 * when (0028,0004),Photometric Interpretation = [PALETTE COLOR ]
1130 * @ return bit number of each LUT item
1132 int File::GetLUTNbits()
1134 std::vector<std::string> tokens;
1137 //Just hope Lookup Table Desc-Red = Lookup Table Desc-Red
1138 // = Lookup Table Desc-Blue
1139 // Consistency already checked in GetLUTLength
1140 std::string lutDescription = GetEntryValue(0x0028,0x1101);
1141 if ( lutDescription == GDCM_UNFOUND )
1146 tokens.clear(); // clean any previous value
1147 Util::Tokenize ( lutDescription, tokens, "\\" );
1148 //LutLength=atoi(tokens[0].c_str());
1149 //LutDepth=atoi(tokens[1].c_str());
1151 lutNbits = atoi( tokens[2].c_str() );
1158 *\brief gets the info from 0028,1052 : Rescale Intercept
1159 * @return Rescale Intercept
1161 float File::GetRescaleIntercept()
1163 float resInter = 0.;
1164 /// 0028 1052 DS IMG Rescale Intercept
1165 const std::string &strRescInter = GetEntryValue(0x0028,0x1052);
1166 if ( strRescInter != GDCM_UNFOUND )
1168 if ( sscanf( strRescInter.c_str(), "%f ", &resInter) != 1 )
1170 // bug in the element 0x0028,0x1052
1171 gdcmWarningMacro( "Rescale Intercept (0028,1052) is empty." );
1179 *\brief gets the info from 0028,1053 : Rescale Slope
1180 * @return Rescale Slope
1182 float File::GetRescaleSlope()
1184 float resSlope = 1.;
1185 //0028 1053 DS IMG Rescale Slope
1186 std::string strRescSlope = GetEntryValue(0x0028,0x1053);
1187 if ( strRescSlope != GDCM_UNFOUND )
1189 if ( sscanf( strRescSlope.c_str(), "%f ", &resSlope) != 1 )
1191 // bug in the element 0x0028,0x1053
1192 gdcmWarningMacro( "Rescale Slope (0028,1053) is empty.");
1200 * \brief This function is intended to user who doesn't want
1201 * to have to manage a LUT and expects to get an RBG Pixel image
1202 * (or a monochrome one ...)
1203 * \warning to be used with GetImagePixels()
1204 * @return 1 if Gray level, 3 if Color (RGB, YBR, *or PALETTE COLOR*)
1206 int File::GetNumberOfScalarComponents()
1208 if ( GetSamplesPerPixel() == 3 )
1213 // 0028 0100 US IMG Bits Allocated
1214 // (in order no to be messed up by old RGB images)
1215 if ( GetEntryValue(0x0028,0x0100) == "24" )
1220 std::string strPhotometricInterpretation = GetEntryValue(0x0028,0x0004);
1222 if ( ( strPhotometricInterpretation == "PALETTE COLOR ") )
1224 if ( HasLUT() )// PALETTE COLOR is NOT enough
1234 // beware of trailing space at end of string
1235 // DICOM tags are never of odd length
1236 if ( strPhotometricInterpretation == GDCM_UNFOUND ||
1237 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME1") ||
1238 Util::DicomStringEqual(strPhotometricInterpretation, "MONOCHROME2") )
1244 // we assume that *all* kinds of YBR are dealt with
1250 * \brief This function is intended to user that DOESN'T want
1251 * to get RGB pixels image when it's stored as a PALETTE COLOR image
1252 * - the (vtk) user is supposed to know how deal with LUTs -
1253 * \warning to be used with GetImagePixelsRaw()
1254 * @return 1 if Gray level, 3 if Color (RGB or YBR - NOT 'PALETTE COLOR' -)
1256 int File::GetNumberOfScalarComponentsRaw()
1258 // 0028 0100 US IMG Bits Allocated
1259 // (in order no to be messed up by old RGB images)
1260 if ( File::GetEntryValue(0x0028,0x0100) == "24" )
1265 // we assume that *all* kinds of YBR are dealt with
1266 return GetSamplesPerPixel();
1270 * \brief Recover the offset (from the beginning of the file)
1271 * of *image* pixels (not *icone image* pixels, if any !)
1272 * @return Pixel Offset
1274 size_t File::GetPixelOffset()
1276 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1279 return pxlElement->GetOffset();
1283 gdcmDebugMacro( "Big trouble : Pixel Element ("
1284 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1290 * \brief Recover the pixel area length (in Bytes)
1291 * @return Pixel Element Length, as stored in the header
1292 * (NOT the memory space necessary to hold the Pixels
1293 * -in case of embeded compressed image-)
1294 * 0 : NOT USABLE file. The caller has to check.
1296 size_t File::GetPixelAreaLength()
1298 DocEntry *pxlElement = GetDocEntry(GrPixel, NumPixel);
1301 return pxlElement->GetLength();
1305 gdcmDebugMacro( "Big trouble : Pixel Element ("
1306 << std::hex << GrPixel<<","<< NumPixel<< ") NOT found" );
1312 * \brief Adds the characteristics of a new element we want to anonymize
1313 * @param group Group number of the target tag.
1314 * @param elem Element number of the target tag.
1315 * @param value new value (string) to substitute with
1317 void File::AddAnonymizeElement (uint16_t group, uint16_t elem,
1318 std::string const &value)
1324 UserAnonymizeList.push_back(el);
1328 * \brief Overwrites in the file the values of the DicomElements
1331 void File::AnonymizeNoLoad()
1333 std::fstream *fp = new std::fstream(Filename.c_str(),
1334 std::ios::in | std::ios::out | std::ios::binary);
1338 uint32_t valLgth = 0;
1339 std::string *spaces;
1340 for (ListElements::iterator it = UserAnonymizeList.begin();
1341 it != UserAnonymizeList.end();
1344 d = GetDocEntry( (*it).Group, (*it).Elem);
1349 if ( dynamic_cast<SeqEntry *>(d) )
1351 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1355 offset = d->GetOffset();
1356 lgth = d->GetLength();
1359 spaces = new std::string( lgth-valLgth, ' ');
1360 (*it).Value = (*it).Value + *spaces;
1363 fp->seekp( offset, std::ios::beg );
1364 fp->write( (*it).Value.c_str(), lgth );
1372 * \brief anonymize a File (remove Patient's personal info passed with
1373 * AddAnonymizeElement()
1374 * \note You cannot Anonymize a BinEntry (to be fixed)
1376 bool File::AnonymizeFile()
1378 // If Anonymisation list is empty, let's perform some basic anonymization
1379 if ( UserAnonymizeList.begin() == UserAnonymizeList.end() )
1381 // If exist, replace by spaces
1382 SetValEntry (" ",0x0010, 0x2154); // Telephone
1383 SetValEntry (" ",0x0010, 0x1040); // Adress
1384 SetValEntry (" ",0x0010, 0x0020); // Patient ID
1386 DocEntry* patientNameHE = GetDocEntry (0x0010, 0x0010);
1388 if ( patientNameHE ) // we replace it by Study Instance UID (why not ?)
1390 std::string studyInstanceUID = GetEntryValue (0x0020, 0x000d);
1391 if ( studyInstanceUID != GDCM_UNFOUND )
1393 SetValEntry(studyInstanceUID, 0x0010, 0x0010);
1397 SetValEntry("anonymized", 0x0010, 0x0010);
1404 for (ListElements::iterator it = UserAnonymizeList.begin();
1405 it != UserAnonymizeList.end();
1408 d = GetDocEntry( (*it).Group, (*it).Elem);
1413 if ( dynamic_cast<SeqEntry *>(d) )
1415 gdcmWarningMacro( "You cannot 'Anonymize' a SeqEntry ");
1419 if ( dynamic_cast<BinEntry *>(d) )
1421 gdcmWarningMacro( "To 'Anonymize' a BinEntry, better use AnonymizeNoLoad (FIXME) ");
1425 SetValEntry ((*it).Value, (*it).Group, (*it).Elem);
1429 // In order to make definitively impossible any further identification
1430 // remove or replace all the stuff that contains a Date
1432 //0008 0012 DA ID Instance Creation Date
1433 //0008 0020 DA ID Study Date
1434 //0008 0021 DA ID Series Date
1435 //0008 0022 DA ID Acquisition Date
1436 //0008 0023 DA ID Content Date
1437 //0008 0024 DA ID Overlay Date
1438 //0008 0025 DA ID Curve Date
1439 //0008 002a DT ID Acquisition Datetime
1440 //0018 9074 DT ACQ Frame Acquisition Datetime
1441 //0018 9151 DT ACQ Frame Reference Datetime
1442 //0018 a002 DT ACQ Contribution Date Time
1443 //0020 3403 SH REL Modified Image Date (RET)
1444 //0032 0032 DA SDY Study Verified Date
1445 //0032 0034 DA SDY Study Read Date
1446 //0032 1000 DA SDY Scheduled Study Start Date
1447 //0032 1010 DA SDY Scheduled Study Stop Date
1448 //0032 1040 DA SDY Study Arrival Date
1449 //0032 1050 DA SDY Study Completion Date
1450 //0038 001a DA VIS Scheduled Admission Date
1451 //0038 001c DA VIS Scheduled Discharge Date
1452 //0038 0020 DA VIS Admitting Date
1453 //0038 0030 DA VIS Discharge Date
1454 //0040 0002 DA PRC Scheduled Procedure Step Start Date
1455 //0040 0004 DA PRC Scheduled Procedure Step End Date
1456 //0040 0244 DA PRC Performed Procedure Step Start Date
1457 //0040 0250 DA PRC Performed Procedure Step End Date
1458 //0040 2004 DA PRC Issue Date of Imaging Service Request
1459 //0040 4005 DT PRC Scheduled Procedure Step Start Date and Time
1460 //0040 4011 DT PRC Expected Completion Date and Time
1461 //0040 a030 DT PRC Verification Date Time
1462 //0040 a032 DT PRC Observation Date Time
1463 //0040 a120 DT PRC DateTime
1464 //0040 a121 DA PRC Date
1465 //0040 a13a DT PRC Referenced Datetime
1466 //0070 0082 DA ??? Presentation Creation Date
1467 //0100 0420 DT ??? SOP Autorization Date and Time
1468 //0400 0105 DT ??? Digital Signature DateTime
1469 //2100 0040 DA PJ Creation Date
1470 //3006 0008 DA SSET Structure Set Date
1471 //3008 0024 DA ??? Treatment Control Point Date
1472 //3008 0054 DA ??? First Treatment Date
1473 //3008 0056 DA ??? Most Recent Treatment Date
1474 //3008 0162 DA ??? Safe Position Exit Date
1475 //3008 0166 DA ??? Safe Position Return Date
1476 //3008 0250 DA ??? Treatment Date
1477 //300a 0006 DA RT RT Plan Date
1478 //300a 022c DA RT Air Kerma Rate Reference Date
1479 //300e 0004 DA RT Review Date
1485 * \brief Performs some consistency checking on various 'File related'
1486 * (as opposed to 'DicomDir related') entries
1487 * then writes in a file all the (Dicom Elements) included the Pixels
1488 * @param fileName file name to write to
1489 * @param writetype type of the file to be written
1490 * (ACR, ExplicitVR, ImplicitVR)
1492 bool File::Write(std::string fileName, FileType writetype)
1494 std::ofstream *fp = new std::ofstream(fileName.c_str(),
1495 std::ios::out | std::ios::binary);
1498 gdcmWarningMacro("Failed to open (write) File: " << fileName.c_str());
1502 // Entry : 0002|0000 = group length -> recalculated
1503 ValEntry*e0000 = GetValEntry(0x0002,0x0000);
1506 std::ostringstream sLen;
1507 sLen << ComputeGroup0002Length( );
1508 e0000->SetValue(sLen.str());
1511 int i_lgPix = GetEntryLength(GrPixel, NumPixel);
1514 // no (GrPixel, NumPixel) element
1515 std::string s_lgPix = Util::Format("%d", i_lgPix+12);
1516 s_lgPix = Util::DicomString( s_lgPix.c_str() );
1517 InsertValEntry(s_lgPix,GrPixel, 0x0000);
1520 Document::WriteContent(fp, writetype);
1528 //-----------------------------------------------------------------------------
1532 //-----------------------------------------------------------------------------
1535 * \brief Parse pixel data from disk of [multi-]fragment RLE encoding.
1536 * Compute the RLE extra information and store it in \ref RLEInfo
1537 * for later pixel retrieval usage.
1539 void File::ComputeRLEInfo()
1541 std::string ts = GetTransferSyntax();
1542 if ( !Global::GetTS()->IsRLELossless(ts) )
1547 // Encoded pixel data: for the time being we are only concerned with
1548 // Jpeg or RLE Pixel data encodings.
1549 // As stated in PS 3.5-2003, section 8.2 p44:
1550 // "If sent in Encapsulated Format (i.e. other than the Native Format) the
1551 // value representation OB is used".
1552 // Hence we expect an OB value representation. Concerning OB VR,
1553 // the section PS 3.5-2003, section A.4.c p 58-59, states:
1554 // "For the Value Representations OB and OW, the encoding shall meet the
1555 // following specifications depending on the Data element tag:"
1557 // - the first item in the sequence of items before the encoded pixel
1558 // data stream shall be basic offset table item. The basic offset table
1559 // item value, however, is not required to be present"
1560 ReadEncapsulatedBasicOffsetTable();
1562 // Encapsulated RLE Compressed Images (see PS 3.5-2003, Annex G)
1563 // Loop on the individual frame[s] and store the information
1564 // on the RLE fragments in a RLEFramesInfo.
1565 // Note: - when only a single frame is present, this is a
1567 // - when more than one frame are present, then we are in
1568 // the case of a multi-frame image.
1572 while ( (frameLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1574 // Since we have read the basic offset table, let's check the value were correct
1575 // or else produce a warning:
1576 if ( BasicOffsetTableItemValue )
1578 // If a BasicOffsetTableItemValue was read
1579 uint32_t individualLength = BasicOffsetTableItemValue[i];
1580 assert( individualLength == sum ); // REMOVE that if this is a problem
1581 if( individualLength != sum )
1583 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght" );
1585 sum += frameLength + 8;
1588 // Parse the RLE Header and store the corresponding RLE Segment
1589 // Offset Table information on fragments of this current Frame.
1590 // Note that the fragment pixels themselves are not loaded
1591 // (but just skipped).
1592 long frameOffset = Fp->tellg();
1594 uint32_t nbRleSegments = ReadInt32();
1595 if ( nbRleSegments > 16 )
1597 // There should be at most 15 segments (refer to RLEFrame class)
1598 gdcmWarningMacro( "Too many segments.");
1601 uint32_t rleSegmentOffsetTable[16];
1602 for( int k = 1; k <= 15; k++ )
1604 rleSegmentOffsetTable[k] = ReadInt32();
1607 // Deduce from both RLE Header and frameLength
1608 // the fragment length, and again store this info
1609 // in a RLEFramesInfo.
1610 long rleSegmentLength[15];
1611 // skipping (not reading) RLE Segments
1612 if ( nbRleSegments > 1)
1614 for(unsigned int k = 1; k <= nbRleSegments-1; k++)
1616 rleSegmentLength[k] = rleSegmentOffsetTable[k+1]
1617 - rleSegmentOffsetTable[k];
1618 SkipBytes(rleSegmentLength[k]);
1622 rleSegmentLength[nbRleSegments] = frameLength
1623 - rleSegmentOffsetTable[nbRleSegments];
1624 SkipBytes(rleSegmentLength[nbRleSegments]);
1626 // Store the collected info
1627 RLEFrame *newFrame = new RLEFrame;
1628 newFrame->SetNumberOfFragments(nbRleSegments);
1629 for( unsigned int uk = 1; uk <= nbRleSegments; uk++ )
1631 newFrame->SetOffset(uk,frameOffset + rleSegmentOffsetTable[uk]);
1632 newFrame->SetLength(uk,rleSegmentLength[uk]);
1634 RLEInfo->AddFrame(newFrame);
1637 // Make sure that we encounter a 'Sequence Delimiter Item'
1638 // at the end of the item :
1639 if ( !ReadTag(0xfffe, 0xe0dd) )
1641 gdcmWarningMacro( "No sequence delimiter item at end of RLE item sequence");
1646 * \brief Parse pixel data from disk of [multi-]fragment Jpeg encoding.
1647 * Compute the jpeg extra information (fragment[s] offset[s] and
1648 * length) and store it[them] in \ref JPEGInfo for later pixel
1651 void File::ComputeJPEGFragmentInfo()
1653 // If you need to, look for comments of ComputeRLEInfo().
1654 std::string ts = GetTransferSyntax();
1655 if ( ! Global::GetTS()->IsJPEG(ts) )
1660 ReadEncapsulatedBasicOffsetTable();
1662 // Loop on the fragments[s] and store the parsed information in a
1664 long fragmentLength;
1667 while ( (fragmentLength = ReadTagLength(0xfffe, 0xe000)) != 0 )
1669 // Since we have read the basic offset table, let's check the value were correct
1670 // or else produce a warning:
1671 // A.4 Transfer syntaxes for encapsulation of encoded pixel data:
1672 // When the Item Value is present, the Basic Offset Table Item Value shall contain
1673 // concatenated 32-bit unsigned integer values that are byte offsets to the first
1674 // byte of the Item Tag of the first fragment for each frame in the Sequence of
1675 // Items. These offsets are measured from the first byte of the first Item Tag
1676 // following the Basic Offset Table item (See Table A.4-2).
1678 if ( BasicOffsetTableItemValue )
1680 // If a BasicOffsetTableItemValue was read
1681 uint32_t individualLength = BasicOffsetTableItemValue[i];
1682 //assert( individualLength == sum ); // Seems like 00191113.dcm is off by one ??
1683 if( individualLength != sum )
1685 gdcmWarningMacro( "BasicOffsetTableItemValue differs from the fragment lenght:" <<
1686 individualLength << " != " << sum );
1688 sum += fragmentLength + 8;
1692 long fragmentOffset = Fp->tellg();
1693 // Store the collected info
1694 JPEGFragment *newFragment = new JPEGFragment;
1695 newFragment->SetOffset(fragmentOffset);
1696 newFragment->SetLength(fragmentLength);
1697 JPEGInfo->AddFragment(newFragment);
1699 SkipBytes(fragmentLength);
1702 // Make sure that we encounter a 'Sequence Delimiter Item'
1703 // at the end of the item :
1704 if ( !ReadTag(0xfffe, 0xe0dd) )
1706 gdcmWarningMacro( "No sequence delimiter item at end of JPEG item sequence");
1711 * \brief Assuming the internal file pointer \ref Document::Fp
1712 * is placed at the beginning of a tag check whether this
1713 * tag is (TestGroup, TestElem).
1714 * \warning On success the internal file pointer \ref Document::Fp
1715 * is modified to point after the tag.
1716 * On failure (i.e. when the tag wasn't the expected tag
1717 * (TestGroup, TestElem) the internal file pointer
1718 * \ref Document::Fp is restored to it's original position.
1719 * @param testGroup The expected group of the tag.
1720 * @param testElem The expected Element of the tag.
1721 * @return True on success, false otherwise.
1723 bool File::ReadTag(uint16_t testGroup, uint16_t testElem)
1725 long positionOnEntry = Fp->tellg();
1726 long currentPosition = Fp->tellg(); // On debugging purposes
1728 // Read the Item Tag group and element, and make
1729 // sure they are what we expected:
1730 uint16_t itemTagGroup;
1731 uint16_t itemTagElem;
1734 itemTagGroup = ReadInt16();
1735 itemTagElem = ReadInt16();
1737 catch ( FormatError /*e*/ )
1739 //std::cerr << e << std::endl;
1742 if ( itemTagGroup != testGroup || itemTagElem != testElem )
1744 gdcmWarningMacro( "Wrong Item Tag found:"
1745 << " We should have found tag ("
1746 << std::hex << testGroup << "," << testElem << ")" << std::endl
1747 << " but instead we encountered tag ("
1748 << std::hex << itemTagGroup << "," << itemTagElem << ")"
1749 << " at address: " << " 0x(" << (unsigned int)currentPosition << ")"
1751 Fp->seekg(positionOnEntry, std::ios::beg);
1759 * \brief Assuming the internal file pointer \ref Document::Fp
1760 * is placed at the beginning of a tag (TestGroup, TestElement),
1761 * read the length associated to the Tag.
1762 * \warning On success the internal file pointer \ref Document::Fp
1763 * is modified to point after the tag and it's length.
1764 * On failure (i.e. when the tag wasn't the expected tag
1765 * (TestGroup, TestElement) the internal file pointer
1766 * \ref Document::Fp is restored to it's original position.
1767 * @param testGroup The expected Group of the tag.
1768 * @param testElem The expected Element of the tag.
1769 * @return On success returns the length associated to the tag. On failure
1772 uint32_t File::ReadTagLength(uint16_t testGroup, uint16_t testElem)
1775 if ( !ReadTag(testGroup, testElem) )
1780 //// Then read the associated Item Length
1781 long currentPosition = Fp->tellg();
1782 uint32_t itemLength = ReadInt32();
1784 gdcmWarningMacro( "Basic Item Length is: "
1785 << itemLength << std::endl
1786 << " at address: " << std::hex << (unsigned int)currentPosition);
1792 * \brief When parsing the Pixel Data of an encapsulated file, read
1793 * the basic offset table (when present, and BTW dump it).
1795 void File::ReadEncapsulatedBasicOffsetTable()
1797 //// Read the Basic Offset Table Item Tag length...
1798 uint32_t itemLength = ReadTagLength(0xfffe, 0xe000);
1800 // When present, read the basic offset table itself.
1801 // Notes: - since the presence of this basic offset table is optional
1802 // we can't rely on it for the implementation, and we will simply
1803 // trash it's content (when present).
1804 // - still, when present, we could add some further checks on the
1805 // lengths, but we won't bother with such fuses for the time being.
1806 if ( itemLength != 0 )
1808 char *charBasicOffsetTableItemValue = new char[itemLength];
1809 Fp->read(charBasicOffsetTableItemValue, itemLength);
1810 unsigned int nbEntries = itemLength/4;
1811 assert( nbEntries*4 == itemLength); // Make sure this is a multiple
1812 BasicOffsetTableItemValue = new uint32_t[nbEntries];
1814 for (unsigned int i=0; i < nbEntries; i++ )
1816 BasicOffsetTableItemValue[i] = *((uint32_t*)(&charBasicOffsetTableItemValue[4*i]));
1817 #if defined(GDCM_WORDS_BIGENDIAN) || defined(GDCM_FORCE_BIGENDIAN_EMULATION)
1818 uint32_t val = BasicOffsetTableItemValue[i];
1819 BasicOffsetTableItemValue[i]
1820 = ( (val<<24) | ((val<<8) & 0x00ff0000) |
1821 ((val>>8) & 0x0000ff00) | (val>>24) );
1823 gdcmWarningMacro( "Read one length for: " <<
1824 std::hex << BasicOffsetTableItemValue[i] );
1827 delete[] charBasicOffsetTableItemValue;
1831 // These are the deprecated method that one day should be removed (after the next release)
1833 #ifndef GDCM_LEGACY_REMOVE
1835 * \brief Constructor (DEPRECATED : temporaryly kept not to break the API)
1836 * @param filename name of the file whose header we want to analyze
1837 * @deprecated do not use any longer
1839 File::File( std::string const &filename )
1842 RLEInfo = new RLEFramesInfo;
1843 JPEGInfo = new JPEGFragmentsInfo;
1845 SetFileName( filename );
1846 Load( ); // gdcm::Document is first Loaded, then the 'File part'
1850 * \brief Loader. (DEPRECATED : temporaryly kept not to break the API)
1851 * @param fileName file to be open for parsing
1852 * @return false if file cannot be open or no swap info was found,
1853 * or no tag was found.
1854 * @deprecated Use the Load() [ + SetLoadMode() ] + SetFileName() functions instead
1856 bool File::Load( std::string const &fileName )
1858 GDCM_LEGACY_REPLACED_BODY(File::Load(std::string), "1.2",
1860 SetFileName( fileName );
1861 if ( ! this->Document::Load( ) )
1864 return DoTheLoadingJob( );
1868 //-----------------------------------------------------------------------------
1871 //-----------------------------------------------------------------------------
1872 } // end namespace gdcm