public bool IsStoredTag(uint tag) { DicomTag dicomTag = DicomTagDictionary.GetDicomTag(tag); if (dicomTag == null) { return(false); } return(IsStoredTag(dicomTag)); }
public static ColumnDefinition GetColumnDefinition(uint dicomTag) { DicomTag tag = DicomTagDictionary.GetDicomTag(dicomTag); if (tag == null) { tag = new DicomTag(dicomTag, string.Empty, string.Empty, DicomVr.UNvr, false, uint.MinValue, uint.MaxValue, false); } return(GetColumnDefinition(tag)); }
private static string GetTagName(uint tag) { DicomTag dcmTag = DicomTagDictionary.GetDicomTag(tag); if (dcmTag != null) { return(dcmTag.ToString()); } return(String.Format("({0}) Unknown", tag.ToString("X8"))); }
private static DicomTag NewTag(uint tag) { DicomTag returnTag = DicomTagDictionary.GetDicomTag(tag); if (returnTag == null) { returnTag = new DicomTag(tag, "Unknown Tag", "UnknownTag", DicomVr.UNvr, false, 1, uint.MaxValue, false); } return(returnTag); }
public DicomAttribute this[uint tag] { get { return(this[DicomTagDictionary.GetDicomTag(tag)]); } set { this[DicomTagDictionary.GetDicomTag(tag)] = value; } }
public bool TryGetAttribute(uint tag, out DicomAttribute attribute) { attribute = DicomTagDictionary.GetDicomTag(tag).CreateDicomAttribute(); switch (tag) { case DicomTags.ModalitiesInStudy: attribute.Values = study.ModalitiesInStudy; return(true); case DicomTags.StudyDescription: attribute.SetStringValue(study.StudyDescription); return(true); case DicomTags.AccessionNumber: attribute.SetStringValue(study.AccessionNumber); return(true); case DicomTags.NumberOfStudyRelatedInstances: attribute.SetInt32(0, study.NumberOfStudyRelatedInstances); return(true); case DicomTags.NumberOfStudyRelatedSeries: attribute.SetInt32(0, study.NumberOfStudyRelatedSeries); return(true); case DicomTags.PatientsAge: attribute.SetStringValue(study.PatientsAge); return(true); case DicomTags.ReferringPhysiciansName: attribute.SetStringValue(study.ReferringPhysiciansName); return(true); case DicomTags.SopClassesInStudy: attribute.Values = study.SopClassesInStudy; return(true); case DicomTags.StudyId: attribute.SetStringValue(study.StudyId); return(true); case DicomTags.StudyDate: attribute.SetStringValue(study.StudyDate); return(true); case DicomTags.StudyTime: attribute.SetStringValue(study.StudyTime); return(true); default: return(false); } }
public Expression CreateExpression(string text) { if (text.StartsWith("$")) { DicomTag tag = DicomTagDictionary.GetDicomTag(text.Substring(1)); if (tag == null) { throw new XmlSpecificationCompilerException("Invalid DICOM tag: " + text); } } return(new DicomExpression(text)); }
/// <summary> /// Creates an in-memory DICOM image /// </summary> /// <returns></returns> private static DicomFile CreateDicomImage(int rows = 20, int columns = 30, bool bitsAllocated16 = true, bool signed = false, int numberOfFrames = 1, Endian endian = Endian.Little, bool useOB = false) { var sopClassUid = bitsAllocated16 ? SopClass.MultiFrameGrayscaleWordSecondaryCaptureImageStorageUid : SopClass.MultiFrameGrayscaleByteSecondaryCaptureImageStorageUid; var sopInstanceUid = DicomUid.GenerateUid().UID; var dcf = new DicomFile(); dcf.MediaStorageSopClassUid = sopClassUid; dcf.MediaStorageSopInstanceUid = sopInstanceUid; dcf.TransferSyntax = endian == Endian.Little ? TransferSyntax.ExplicitVrLittleEndian : TransferSyntax.ExplicitVrBigEndian; dcf.DataSet[DicomTags.PatientId].SetStringValue("TEST"); dcf.DataSet[DicomTags.PatientsName].SetStringValue("TEST"); dcf.DataSet[DicomTags.StudyInstanceUid].SetStringValue(DicomUid.GenerateUid().UID); dcf.DataSet[DicomTags.StudyId].SetStringValue("TEST"); dcf.DataSet[DicomTags.StudyDescription].SetStringValue("TEST"); dcf.DataSet[DicomTags.SeriesInstanceUid].SetStringValue(DicomUid.GenerateUid().UID); dcf.DataSet[DicomTags.SeriesNumber].SetInt32(0, 1); dcf.DataSet[DicomTags.SeriesDescription].SetStringValue("TEST"); dcf.DataSet[DicomTags.SopClassUid].SetStringValue(sopClassUid); dcf.DataSet[DicomTags.SopInstanceUid].SetStringValue(sopInstanceUid); dcf.DataSet[DicomTags.InstanceNumber].SetInt32(0, 1); var frameSize = rows * columns * (bitsAllocated16 ? 2 : 1); var data = new byte[numberOfFrames * frameSize]; for (var n = 0; n < numberOfFrames; ++n) { var value = (byte)(0xFF & (n + 0x80)); for (var k = 0; k < frameSize; ++k) { data[n * frameSize + k] = value; } } var pixelDataTag = DicomTagDictionary.GetDicomTag(DicomTags.PixelData); pixelDataTag = new DicomTag(pixelDataTag.TagValue, pixelDataTag.Name, pixelDataTag.VariableName, useOB ? DicomVr.OBvr : DicomVr.OWvr, pixelDataTag.MultiVR, pixelDataTag.VMLow, pixelDataTag.VMHigh, pixelDataTag.Retired); dcf.DataSet[DicomTags.PhotometricInterpretation].SetStringValue(PhotometricInterpretation.Monochrome2.Code); dcf.DataSet[DicomTags.SamplesPerPixel].SetInt32(0, 1); dcf.DataSet[DicomTags.PixelRepresentation].SetInt32(0, signed ? 1 : 0); dcf.DataSet[DicomTags.BitsAllocated].SetInt32(0, bitsAllocated16 ? 16 : 8); dcf.DataSet[DicomTags.BitsStored].SetInt32(0, bitsAllocated16 ? 16 : 8); dcf.DataSet[DicomTags.HighBit].SetInt32(0, bitsAllocated16 ? 15 : 7); dcf.DataSet[DicomTags.Rows].SetInt32(0, rows); dcf.DataSet[DicomTags.Columns].SetInt32(0, columns); dcf.DataSet[DicomTags.NumberOfFrames].SetInt32(0, numberOfFrames); dcf.DataSet[pixelDataTag].Values = data; return(dcf); }
public void TestTagMappingBySopClass() { foreach (var uid in _multiframeSopClassUids) { var sopClass = SopClass.GetSopClass(uid).Name; var functionalGroups = FunctionalGroupDescriptor.GetApplicableFunctionalGroups(uid).ToList(); var tagGroups = functionalGroups.Select(f => f.Create()) .SelectMany(f => f.NestedTags.Select(t => new { TagValue = t, FunctionalGroup = f })) .GroupBy(u => u.TagValue).OrderBy(u => u.Key).ToList(); foreach (var group in tagGroups) { var dcmTag = DicomTagDictionary.GetDicomTag(group.Key); // asserts that any tag defined in 'singleton' functional groups (those whose sequence can have at most 1 item) should have at least some mapping var fgType = FunctionalGroupDescriptor.GetFunctionalGroupByTag(uid, group.Key); if (fgType == null) { foreach (var entry in group) { Assert.IsTrue(entry.FunctionalGroup.CanHaveMultipleItems, "At least one singleton functional group defines tag {0} for SOP class {1}", dcmTag, sopClass); } } // explicitly assert the mapping for any tag defined by multiple 'singleton' functional groups - so that if new tags are introduced later, we would explicitly consider what is the correct mapping if (group.Count(g => !g.FunctionalGroup.CanHaveMultipleItems) > 1) { const string wrongMapMsg = "SOP Class {0} maps tag {1} to the wrong functional group"; if (uid == SopClass.EnhancedXaImageStorageUid) { switch (group.Key) { case DicomTags.TableHorizontalRotationAngle: case DicomTags.TableHeadTiltAngle: case DicomTags.TableCradleTiltAngle: Assert.AreEqual(new FunctionalGroupDescriptor(typeof(XRayTablePositionFunctionalGroup)), fgType, wrongMapMsg, sopClass, dcmTag); break; default: Assert.Fail("SOP Class {0} shouldn't have an ambiguous mapping for tag {1} - if new tags were added, please explicitly update the expected mapping in this unit test", sopClass, dcmTag); break; } } else { Assert.Fail("SOP Class {0} shouldn't have any ambiguous mappings - if new tags were added, please explicitly update the expected mapping in this unit test", sopClass); } } } } }
private void PopulateField(uint tag, IDicomAttributeProvider attributeProvider) { DicomAttribute attr; if (attributeProvider.TryGetAttribute(tag, out attr)) { AddField(new ImageSetField(attr)); } else { // add default value AddField(new ImageSetField(DicomTagDictionary.GetDicomTag(tag).CreateDicomAttribute())); } }
/// <summary> /// Fixes the VR of the specified DICOM tag, which is especially important for multi-VR tags. /// </summary> private static DicomTag FixVR(uint tag, DicomVr newVR) { var dicomTag = DicomTagDictionary.GetDicomTag(tag); if (dicomTag.VR == newVR) { return(dicomTag); } if (!dicomTag.MultiVR) { throw new ArgumentException("The specified DICOM tag does not support multiple VRs.", "tag"); } return(new DicomTag(dicomTag.TagValue, dicomTag.Name, dicomTag.VariableName, newVR, true, dicomTag.VMLow, dicomTag.VMHigh, dicomTag.Retired)); }
static void AddDicomLength(uint tag) { DicomTag dTag = DicomTagDictionary.GetDicomTag(tag); // For PN VR tags, we're only storing 64 bit lengths, whereas the max length is 64. if (dTag.VR.Equals(DicomVr.PNvr)) { _maxLengths.Add(tag, 64); } else { _maxLengths.Add(tag, dTag.VR.MaximumLength); } }
public void ConvertAttributeToUN(DicomAttributeCollection theSet, uint tag) { ByteBuffer theData = theSet[tag].GetByteBuffer(TransferSyntax.ImplicitVrLittleEndian, theSet.SpecificCharacterSet); DicomTag baseTag = DicomTagDictionary.GetDicomTag(tag); DicomTag theTag = new DicomTag(tag, baseTag.Name, baseTag.VariableName, DicomVr.UNvr, baseTag.MultiVR, baseTag.VMLow, baseTag.VMHigh, baseTag.Retired); DicomAttribute unAttrib = DicomVr.UNvr.CreateDicomAttribute(theTag, theData); theSet[tag] = unAttrib; }
public AddOriginalAttributes() { UpdateEntry = new ImageLevelUpdateEntry() { TagPath = new DicomTagPath() { Tag = DicomTagDictionary.GetDicomTag(DicomTags.OriginalAttributesSequence) }, Value = "N/A", OriginalValue = "N/A" }; }
/// <summary> /// Ensures the offset of the data set in the source stream is determined. /// </summary> internal void ParseMetaInfo() { if (MetaInfoFileLength != 0) { return; } var theFile = new DicomFile(); const uint stopTag = DicomTags.RelatedGeneralSopClassUid; theFile.Load(StreamOpener, DicomTagDictionary.GetDicomTag(stopTag), DicomReadOptions.Default); MetaInfoFileLength = theFile.MetaInfoFileLength; }
private static DicomTag LookupDicomTag(string tag) { uint tagValue; if (uint.TryParse(tag, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out tagValue)) { // very simple support for private tags, since the toolkit won't try to read it anyway if (DicomTag.IsPrivateGroup((ushort)(0x00FFFF & (tagValue >> 16)))) { return(new DicomTag(tagValue, "Private Tag", "PrivateTag", DicomVr.UNvr, false, 1, uint.MaxValue, false)); } return(DicomTagDictionary.GetDicomTag(tagValue)); } return(DicomTagDictionary.GetDicomTag(tag)); }
public Expression CreateExpression(string text) { if (text.StartsWith("$")) { var tagArray = text.Split(new[] { '/' }); foreach (var t in tagArray) { DicomTag tag = DicomTagDictionary.GetDicomTag(t.Substring(1)); if (tag == null) { throw new XmlSpecificationCompilerException("Invalid DICOM tag: " + t); } } } return(new DicomExpression(text)); }
internal static DicomTag NewTag(uint tag, DicomVr vr) { var theTag = DicomTagDictionary.GetDicomTag(tag); if (theTag == null) { theTag = new DicomTag(tag, "Unknown tag", "UnknownTag", vr ?? DicomVr.UNvr, false, 1, uint.MaxValue, false); } else if (vr != null && !theTag.VR.Equals(vr)) { theTag = new DicomTag(tag, theTag.Name, theTag.VariableName, vr, theTag.MultiVR, theTag.VMLow, theTag.VMHigh, theTag.Retired); } return(theTag); }
protected DicomTagColumn(DicomTag dicomTag) { _tag = dicomTag.TagValue; _vr = dicomTag.VR.Name; uint tagGroup = (_tag >> 16) & 0x0000FFFF; uint tagElement = _tag & 0x0000FFFF; if (DicomTagDictionary.GetDicomTag(dicomTag.TagValue) == null) { _tagName = string.Format(SR.FormatUnknownDicomTag, tagGroup, tagElement); } else { _tagName = string.Format(SR.FormatDicomTag, tagGroup, tagElement, dicomTag.Name); } }
private void ParseTo(uint tag) { while (_baseCollectionEnumerator != null && _baseCollectionEnumerator.Current.Tag.TagValue <= tag) { _collection[_baseCollectionEnumerator.Current.Tag] = _baseCollectionEnumerator.Current.Copy(); if (!_baseCollectionEnumerator.MoveNext()) { _baseCollectionEnumerator = null; } } while (_instanceXmlEnumerator != null) { XmlNode node = (XmlNode)_instanceXmlEnumerator.Current; String tagString = node.Attributes["Tag"].Value; uint tagValue; if (tagString.StartsWith("$")) { DicomTag dicomTag = DicomTagDictionary.GetDicomTag(tagString.Substring(1)); if (dicomTag == null) { throw new DicomDataException("Invalid tag name when parsing XML: " + tagString); } tagValue = dicomTag.TagValue; } else { tagValue = uint.Parse(tagString, NumberStyles.HexNumber); } if (tagValue <= tag) { ParseAttribute(_collection, node); if (!_instanceXmlEnumerator.MoveNext()) { _instanceXmlEnumerator = null; } } else { break; } } }
public void AssertTagValueChanged(uint tag, string valueToSet, string originalCharacterSet, string expectedNewCharacterSet) { DicomAttributeCollection dataset = new DicomAttributeCollection(); SetupDataSet(dataset, originalCharacterSet); DicomFile file = new DicomFile("test", CreateMetaInfo(), dataset); Assert.AreEqual(originalCharacterSet, file.DataSet[DicomTags.SpecificCharacterSet].ToString()); SetTagCommand cmd = new SetTagCommand(tag, valueToSet); Assert.AreEqual(cmd.CanSaveInUnicode, UnicodeAllowed, "SetTagCommand.CanSaveInUnicode returns an incorrect value"); var sq = new OriginalAttributesSequence { ModifiedAttributesSequence = new DicomSequenceItem(), ModifyingSystem = ProductInformation.Component, ReasonForTheAttributeModification = "CORRECT", AttributeModificationDatetime = Platform.Time, SourceOfPreviousValues = file.SourceApplicationEntityTitle }; Assert.IsTrue(cmd.Apply(file, sq), "SetTagCommand.Apply failed"); var filename = string.Format("Test-{0}.dcm", DicomTagDictionary.GetDicomTag(tag).Name); Assert.IsTrue(file.Save(filename), "Unable to save dicom file"); file = new DicomFile(filename); file.Load(); if (valueToSet == null) { Assert.AreEqual(string.Empty, file.DataSet[tag].ToString()); } else { Assert.AreEqual(valueToSet, file.DataSet[tag].ToString()); } Assert.IsTrue(file.DataSet[DicomTags.SpecificCharacterSet].ToString().Equals(expectedNewCharacterSet)); Delete(filename); }
private void UpdateDialog() { DicomTag entry = DicomTagDictionary.GetDicomTag(_group, _element); if (entry != null) { this.TagName = entry.Name; this.Vr = entry.VR.ToString(); this.VrEnabled = false; } else { this.TagName = "Unknown"; this.Vr = ""; this.VrEnabled = true; } this.AcceptEnabled = this.AllowTagAddition(); }
/// <summary> /// Load enough information from the file to allow negotiation of the association. /// </summary> public void LoadInfo() { if (_infoLoaded) { return; } var theFile = new DicomFile(); const uint stopTag = DicomTags.StudyId; theFile.Load(StreamOpener, DicomTagDictionary.GetDicomTag(stopTag), DicomReadOptions.Default); string sopClassInFile = theFile.DataSet[DicomTags.SopClassUid].ToString(); if (!sopClassInFile.Equals(theFile.SopClass.Uid)) { Platform.Log(LogLevel.Warn, "SOP Class in Meta Info ({0}) does not match SOP Class in DataSet ({1})", theFile.SopClass.Uid, sopClassInFile); _sopClass = SopClass.GetSopClass(sopClassInFile); if (_sopClass == null) { Platform.Log(LogLevel.Warn, "Unknown SOP Class in dataset, reverting to meta info: {0}", sopClassInFile); _sopClass = theFile.SopClass; } } else { _sopClass = theFile.SopClass; } _syntax = theFile.TransferSyntax; // these fields must be loaded for auditing purposes, and LoadFile() may not get called StudyInstanceUid = theFile.DataSet[DicomTags.StudyInstanceUid].GetString(0, string.Empty); SeriesInstanceUid = theFile.DataSet[DicomTags.SeriesInstanceUid].GetString(0, string.Empty); SopInstanceUid = theFile.DataSet[DicomTags.SopInstanceUid].GetString(0, string.Empty); PatientsName = theFile.DataSet[DicomTags.PatientsName].GetString(0, string.Empty); PatientId = theFile.DataSet[DicomTags.PatientId].GetString(0, string.Empty); MetaInfoFileLength = theFile.MetaInfoFileLength; _infoLoaded = true; }
/// <summary> /// Creates an instance of <see cref="SetTagCommand"/> that can be used to update the specified dicom tag with the specified value /// </summary> /// <remarks> /// <see cref="BaseImageLevelUpdateCommand.File"/> must be set prior to <see cref="BaseImageLevelUpdateCommand.OnExecute"></see> /// </remarks> public SetTagCommand(uint tag, string originalValue, string value) : this() { var dicomTag = DicomTagDictionary.GetDicomTag(tag); UpdateEntry.TagPath = new DicomTagPath { Tag = dicomTag }; if (!string.IsNullOrEmpty(value)) { int maxLength = dicomTag.VR.Equals(DicomVr.PNvr) ? 64 : (int)dicomTag.VR.MaximumLength; if (value.Length > maxLength) { value = value.Substring(0, maxLength); } } UpdateEntry.Value = value; UpdateEntry.OriginalValue = originalValue; }
private void UpdateDialog() { DicomTag entry = DicomTagDictionary.GetDicomTag(_group, _element); if (entry != null) { TagName = entry.Name; Vr = entry.VR.ToString(); } else { TagName = "Unknown"; Vr = ""; } AcceptEnabled = AllowTagAddition(); NotifyPropertyChanged("Group"); NotifyPropertyChanged("Element"); NotifyPropertyChanged("TagName"); NotifyPropertyChanged("Vr"); NotifyPropertyChanged("AcceptEnabled"); }
/// <summary> /// Load enough information from the file to allow negotiation of the association. /// </summary> public void LoadInfo() { if (_infoLoaded) { return; } var theFile = new DicomFile(); const uint stopTag = DicomTags.RelatedGeneralSopClassUid; theFile.Load(StreamOpener, DicomTagDictionary.GetDicomTag(stopTag), DicomReadOptions.Default); string sopClassInFile = theFile.DataSet[DicomTags.SopClassUid].ToString(); if (!sopClassInFile.Equals(theFile.SopClass.Uid)) { Platform.Log(LogLevel.Warn, "SOP Class in Meta Info ({0}) does not match SOP Class in DataSet ({1})", theFile.SopClass.Uid, sopClassInFile); _sopClass = SopClass.GetSopClass(sopClassInFile); if (_sopClass == null) { Platform.Log(LogLevel.Warn, "Unknown SOP Class in dataset, reverting to meta info: {0}", sopClassInFile); _sopClass = theFile.SopClass; } } else { _sopClass = theFile.SopClass; } _syntax = theFile.TransferSyntax; SopInstanceUid = theFile.MediaStorageSopInstanceUid; MetaInfoFileLength = theFile.MetaInfoFileLength; _infoLoaded = true; }
public DicomReadStatus Read(DicomTag stopAtTag, DicomReadOptions options) { if (stopAtTag == null) { stopAtTag = new DicomTag(0xFFFFFFFF, "Bogus Tag", "BogusTag", DicomVr.UNvr, false, 1, 1, false); } // Counters: // _remain - bytes remaining in stream // _bytes - estimates bytes to end of dataset // _read - number of bytes read from stream try { BytesNeeded = 0; _remain = _stream.Length - _stream.Position; while (_remain > 0) { if (_inGroup2 && BytesRead >= _endGroup2) { _inGroup2 = false; // Only change if we're still reading the meta info if (Dataset.StartTagValue < DicomTags.TransferSyntaxUid) { TransferSyntax group2Syntax = TransferSyntax.GetTransferSyntax( Dataset[DicomTags.TransferSyntaxUid].GetString(0, String.Empty)); if (group2Syntax == null) { throw new DicomException("Unsupported transfer syntax in group 2 elements"); } TransferSyntax = group2Syntax; } } uint tagValue; if (LastTagRead == null) { if (_remain < 4) { return(NeedMoreData(4)); } _pos = _stream.Position; ushort g = _reader.ReadUInt16(); ushort e = _reader.ReadUInt16(); tagValue = DicomTag.GetTagValue(g, e); if (DicomTag.IsPrivateGroup(g) && e > 0x00ff) { SaveTagRead = LastTagRead = DicomTagDictionary.GetDicomTag(g, e) ?? new DicomTag((uint)g << 16 | e, "Private Tag", "PrivateTag", DicomVr.UNvr, false, 1, uint.MaxValue, false); } else { if (e == 0x0000) { SaveTagRead = LastTagRead = new DicomTag((uint)g << 16 | e, "Group Length", "GroupLength", DicomVr.ULvr, false, 1, 1, false); } else { SaveTagRead = LastTagRead = DicomTagDictionary.GetDicomTag(g, e) ?? new DicomTag((uint)g << 16 | e, "Private Tag", "PrivateTag", DicomVr.UNvr, false, 1, uint.MaxValue, false); } } _remain -= 4; BytesEstimated += 4; BytesRead += 4; } else { tagValue = LastTagRead.TagValue; } if ((tagValue >= stopAtTag.TagValue) && (_sqrs.Count == 0)) // only exit in root message when after stop tag { if (_inGroup2 && tagValue > 0x0002FFFF) { if (_endGroup2 != BytesRead - 4) { Platform.Log(LogLevel.Debug, "File Meta Info Length, {0}, not equal to actual bytes read in file, {1}, overwriting length.", EndGroupTwo, BytesRead - 4); _endGroup2 = BytesRead - 4; } _inGroup2 = false; } EncounteredStopTag = true; return(DicomReadStatus.Success); } bool twoByteLength; if (_vr == null) { if (_syntax.ExplicitVr) { if (LastTagRead == DicomTag.Item || LastTagRead == DicomTag.ItemDelimitationItem || LastTagRead == DicomTag.SequenceDelimitationItem) { _vr = DicomVr.NONE; twoByteLength = _vr.Is16BitLengthField; } else { if (_remain < 2) { return(NeedMoreData(2)); } string vr = new string(_reader.ReadChars(2)); _vr = DicomVr.GetVR(vr); twoByteLength = _vr.Is16BitLengthField; _remain -= 2; BytesEstimated += 2; BytesRead += 2; if (LastTagRead.VR.Equals(DicomVr.UNvr)) { LastTagRead = new DicomTag(LastTagRead.TagValue, "Private Tag", "PrivateTag", _vr, false, 1, uint.MaxValue, false); if (vr.Equals("??")) { twoByteLength = true; } } else if (!LastTagRead.VR.Equals(_vr)) { if (!vr.Equals(" ")) { DicomTag tag = new DicomTag(LastTagRead.TagValue, LastTagRead.Name, LastTagRead.VariableName, _vr, LastTagRead.MultiVR, LastTagRead.VMLow, LastTagRead.VMHigh, LastTagRead.Retired); LastTagRead = tag; ; // TODO, log something } } } } else { _vr = LastTagRead.VR; twoByteLength = _vr.Is16BitLengthField; } if (_vr == DicomVr.UNvr) { if (LastTagRead.IsPrivate) { if (LastTagRead.Element <= 0x00ff && LastTagRead.Element >= 0x0010) { // Reset the tag with the right VR and a more descriptive name. LastTagRead = new DicomTag(LastTagRead.TagValue, "Private Creator Code", "PrivateCreatorCode", DicomVr.LOvr, false, 1, uint.MaxValue, false); // private creator id // Only set the VR to LO for Implicit VR, if we do it for // Explicit VR syntaxes, we would incorrectly read the tag // length below. if (!_syntax.ExplicitVr) { _vr = DicomVr.LOvr; } } else if (_stream.CanSeek && Flags.IsSet(options, DicomReadOptions.AllowSeekingForContext)) { // attempt to identify private sequence by checking if the tag has // an undefined length long pos = _stream.Position; int bytesToCheck = _syntax.ExplicitVr ? 6 : 4; if (_remain >= bytesToCheck) { if (_syntax.ExplicitVr) { _reader.ReadUInt16(); } uint l = _reader.ReadUInt32(); if (l == _undefinedLength) { _vr = DicomVr.SQvr; } } _stream.Position = pos; } } } } else { twoByteLength = _vr.Is16BitLengthField; } // Read the value length if (_len == _undefinedLength) { if (_syntax.ExplicitVr) { if (LastTagRead == DicomTag.Item || LastTagRead == DicomTag.ItemDelimitationItem || LastTagRead == DicomTag.SequenceDelimitationItem) { if (_remain < 4) { return(NeedMoreData(4)); } _len = _reader.ReadUInt32(); _remain -= 4; BytesEstimated += 4; BytesRead += 4; } else { if (twoByteLength) { if (_remain < 2) { return(NeedMoreData(2)); } _len = _reader.ReadUInt16(); _remain -= 2; BytesEstimated += 2; BytesRead += 2; } else { if (_remain < 6) { return(NeedMoreData(6)); } _reader.ReadByte(); _reader.ReadByte(); _len = _reader.ReadUInt32(); _remain -= 6; BytesEstimated += 6; BytesRead += 6; } } } else { if (_remain < 4) { return(NeedMoreData(4)); } _len = _reader.ReadUInt32(); _remain -= 4; BytesEstimated += 4; BytesRead += 4; } if ((_len != _undefinedLength) && !_vr.Equals(DicomVr.SQvr) && !(LastTagRead.Equals(DicomTag.Item) && _fragment == null)) { BytesEstimated += _len; } } // If we have a private creator code, set the VR to LO, because // that is what it is. We must do this after we read the length // so that the 32 bit length is read properly. if ((LastTagRead.IsPrivate) && (_vr.Equals(DicomVr.UNvr)) && (LastTagRead.Element <= 0x00ff)) { _vr = DicomVr.LOvr; } if (_fragment != null) { // In the middle of parsing pixels if (LastTagRead == DicomTag.Item) { if (_remain < _len) { return(NeedMoreData(_remain - _len)); } if (Flags.IsSet(options, DicomReadOptions.StorePixelDataReferences) && _fragment.HasOffsetTable) { FileReference reference = new FileReference(StreamOpener, _stream.Position, _len, _endian, DicomVr.OBvr); DicomFragment fragment = new DicomFragment(reference); _fragment.AddFragment(fragment); if (_stream.CanSeek) { _stream.Seek(_len, SeekOrigin.Current); } else { ConsumeStreamBytes(_stream, _len); } } else { ByteBuffer data = new ByteBuffer(_endian, _len); data.CopyFrom(_stream, (int)_len); if (!_fragment.HasOffsetTable) { _fragment.SetOffsetTable(data); } else { DicomFragment fragment = new DicomFragment(data); _fragment.AddFragment(fragment); } } _remain -= _len; BytesRead += _len; } else if (LastTagRead == DicomTag.SequenceDelimitationItem) { if (_sqrs.Count > 0) { SequenceRecord rec = _sqrs.Peek(); DicomAttributeCollection ds = rec.Current; ds[_fragment.Tag] = _fragment; if (rec.Curlen != _undefinedLength) { long end = rec.Curpos + rec.Curlen; if (_stream.Position >= end) { rec.Current = null; } } } else { Dataset[_fragment.Tag] = _fragment; } _fragment = null; } else { Platform.Log(LogLevel.Error, "Encountered unexpected tag in stream: {0}", LastTagRead.ToString()); // unexpected tag return(DicomReadStatus.UnknownError); } } else if (_sqrs.Count > 0 && (LastTagRead == DicomTag.Item || LastTagRead == DicomTag.ItemDelimitationItem || LastTagRead == DicomTag.SequenceDelimitationItem)) { SequenceRecord rec = _sqrs.Peek(); if (LastTagRead.Equals(DicomTag.Item)) { if (_len != _undefinedLength) { if (_len > _remain) { return(NeedMoreData(_remain - _len)); } } DicomSequenceItem ds; if (rec.Tag.TagValue.Equals(DicomTags.DirectoryRecordSequence)) { DirectoryRecordSequenceItem dr = new DirectoryRecordSequenceItem { Offset = (uint)_pos }; ds = dr; } else { ds = new DicomSequenceItem(); } rec.Current = ds; if (rec.Tag.VR.Equals(DicomVr.UNvr)) { DicomTag tag = new DicomTag(rec.Tag.TagValue, rec.Tag.Name, rec.Tag.VariableName, DicomVr.SQvr, rec.Tag.MultiVR, rec.Tag.VMLow, rec.Tag.VMHigh, rec.Tag.Retired); rec.Parent[tag].AddSequenceItem(ds); } else { rec.Parent[rec.Tag].AddSequenceItem(ds); } // Specific character set is inherited, save it. It will be overwritten // if a new value of the tag is encountered in the sequence. rec.Current.SpecificCharacterSet = rec.Parent.SpecificCharacterSet; // save the sequence length rec.Curpos = _pos + 8; rec.Curlen = _len; _sqrs.Pop(); _sqrs.Push(rec); if (_len != _undefinedLength) { ByteBuffer data = new ByteBuffer(_endian, _len); data.CopyFrom(_stream, (int)_len); data.Stream.Position = 0; _remain -= _len; BytesRead += _len; DicomStreamReader idsr = new DicomStreamReader(data.Stream) { Dataset = ds, TransferSyntax = rec.Tag.VR.Equals(DicomVr.UNvr) ? TransferSyntax.ImplicitVrLittleEndian : _syntax, StreamOpener = StreamOpener }; DicomReadStatus stat = idsr.Read(null, options & ~DicomReadOptions.StorePixelDataReferences); if (stat != DicomReadStatus.Success) { Platform.Log(LogLevel.Error, "Unexpected parsing error ({0}) when reading sequence attribute: {1}.", stat, rec.Tag.ToString()); return(stat); } } } else if (LastTagRead == DicomTag.ItemDelimitationItem) { } else if (LastTagRead == DicomTag.SequenceDelimitationItem) { SequenceRecord rec2 = _sqrs.Pop(); if (rec2.Current == null) { rec2.Parent[rec.Tag].SetNullValue(); } } if (rec.Len != _undefinedLength) { long end = rec.Pos + 8 + rec.Len; if (_syntax.ExplicitVr) { end += 2 + 2; } if (_stream.Position >= end) { _sqrs.Pop(); } } } else { if (_len == _undefinedLength) { if (_vr.Equals(DicomVr.UNvr)) { if (!_syntax.ExplicitVr) { _vr = DicomVr.SQvr; LastTagRead = LastTagRead.IsPrivate ? new DicomTag(LastTagRead.TagValue, "Private Tag", "PrivateTag", DicomVr.SQvr, false, 1, uint.MaxValue, false) : new DicomTag(LastTagRead.TagValue, "Unknown Tag", "UnknownTag", DicomVr.SQvr, false, 1, uint.MaxValue, false); } else { // To handle this case, we'd have to add a new mechanism to transition the parser to implicit VR parsing, // and then return back to implicit once the parsing of the SQ is complete. Platform.Log(LogLevel.Error, "Encountered unknown tag {0}, encoded as undefined length in an Explicit VR transfer syntax at offset {1}. Unable to parse.", LastTagRead, _stream.Position); return(DicomReadStatus.UnknownError); } } if (_vr.Equals(DicomVr.SQvr)) { SequenceRecord rec = new SequenceRecord { Parent = _sqrs.Count > 0 ? _sqrs.Peek().Current : Dataset, Current = null, Tag = LastTagRead, Len = _undefinedLength }; _sqrs.Push(rec); } else { _fragment = new DicomFragmentSequence(LastTagRead); } } else { if (_vr.Equals(DicomVr.SQvr)) { if (_len == 0) { DicomAttributeCollection ds; if (_sqrs.Count > 0) { SequenceRecord rec = _sqrs.Peek(); ds = rec.Current; } else { ds = Dataset; } ds[LastTagRead].SetNullValue(); } else { SequenceRecord rec = new SequenceRecord { Len = _len, Pos = _pos, Tag = LastTagRead, Parent = _sqrs.Count > 0 ? _sqrs.Peek().Current : Dataset }; _sqrs.Push(rec); } } else { if (_remain < _len) { return(NeedMoreData(_len - _remain)); } if ((LastTagRead.TagValue == DicomTags.PixelData) && Flags.IsSet(options, DicomReadOptions.DoNotStorePixelDataInDataSet)) { // Skip PixelData !! if (_stream.CanSeek) { _stream.Seek((int)_len, SeekOrigin.Current); } else { ConsumeStreamBytes(_stream, _len); } _remain -= _len; BytesRead += _len; } else if ((LastTagRead.TagValue == DicomTags.PixelData) && Flags.IsSet(options, DicomReadOptions.StorePixelDataReferences)) { var reference = new FileReference(StreamOpener, _stream.Position, _len, _endian, LastTagRead.VR); if (_stream.CanSeek) { _stream.Seek((int)_len, SeekOrigin.Current); } else { ConsumeStreamBytes(_stream, _len); } DicomAttribute elem; if (LastTagRead.VR.Equals(DicomVr.OWvr)) { elem = new DicomAttributeOW(LastTagRead, reference); } else if (LastTagRead.VR.Equals(DicomVr.OBvr)) { elem = new DicomAttributeOB(LastTagRead, reference); } else if (LastTagRead.VR.Equals(DicomVr.ODvr)) { elem = new DicomAttributeOD(LastTagRead, reference); } else { elem = new DicomAttributeOF(LastTagRead, reference); } if (_sqrs.Count > 0) { SequenceRecord rec = _sqrs.Peek(); DicomAttributeCollection ds = rec.Current; ds[LastTagRead] = elem; if (rec.Curlen != _undefinedLength) { long end = rec.Curpos + rec.Curlen; if (_stream.Position >= end) { rec.Current = null; } } } else { Dataset[LastTagRead] = elem; } _remain -= _len; BytesRead += _len; } else { ByteBuffer bb = new ByteBuffer(_len); // If the tag is impacted by specific character set, // set the encoding properly. if (LastTagRead.VR.SpecificCharacterSet) { if (_sqrs.Count > 0) { SequenceRecord rec = _sqrs.Peek(); bb.SpecificCharacterSet = rec.Current.SpecificCharacterSet; } else { bb.SpecificCharacterSet = Dataset.SpecificCharacterSet; } } if (LastTagRead.VR.Equals(DicomVr.UNvr) && !SaveTagRead.VR.Equals(DicomVr.UNvr) && !SaveTagRead.VR.Equals(DicomVr.SQvr) && Flags.IsSet(options, DicomReadOptions.UseDictionaryForExplicitUN)) { LastTagRead = SaveTagRead; bb.Endian = Endian.Little; } else { bb.Endian = _endian; } bb.CopyFrom(_stream, (int)_len); DicomAttribute elem = LastTagRead.CreateDicomAttribute(bb); _remain -= _len; BytesRead += _len; if (_sqrs.Count > 0) { SequenceRecord rec = _sqrs.Peek(); DicomAttributeCollection ds = rec.Current; if (elem.Tag.TagValue == DicomTags.SpecificCharacterSet) { ds.SpecificCharacterSet = elem.ToString(); } if (LastTagRead.Element == 0x0000) { if (Flags.IsSet(options, DicomReadOptions.KeepGroupLengths)) { ds[LastTagRead] = elem; } } else { ds[LastTagRead] = elem; } if (rec.Curlen != _undefinedLength) { long end = rec.Curpos + rec.Curlen; if (_stream.Position >= end) { rec.Current = null; } } } else { if (LastTagRead.TagValue == DicomTags.FileMetaInformationGroupLength) { // Save the end of the group 2 elements, so that we can automatically // check and change our transfer syntax when needed. _inGroup2 = true; uint group2Len; elem.TryGetUInt32(0, out group2Len); _endGroup2 = BytesRead + group2Len; } else if (LastTagRead.TagValue == DicomTags.SpecificCharacterSet) { Dataset.SpecificCharacterSet = elem.ToString(); } if (LastTagRead.Element == 0x0000) { if (Flags.IsSet(options, DicomReadOptions.KeepGroupLengths)) { Dataset[LastTagRead] = elem; } } else { Dataset[LastTagRead] = elem; } } } } } } LastTagRead = null; _vr = null; _len = _undefinedLength; } return(DicomReadStatus.Success); } catch (EndOfStreamException e) { // should never happen Platform.Log(LogLevel.Error, "Unexpected exception when reading file: {0}", e.ToString()); return(DicomReadStatus.UnknownError); } }
//public DicomFile GetHeader(bool forceComplete) //{ // if (forceComplete) // LoadFullHeader(); //Make sure the full header's loaded. // //Return a copy of whatever we've got. // return new DicomFile(null, MetaInfo.Copy(), DataSet.Copy()); //} //public DicomFile GetCompleteSop() //{ // //Just get the entire thing from the loader. // var args = new LoadDicomFileArgs(StudyInstanceUid, SeriesInstanceUid, SopInstanceUid, true, true); // return DicomFileLoader.LoadDicomFile(args); //} //public IFramePixelData GetFramePixelData(int frameNumber) //{ // var args = new LoadFramePixelDataArgs(this.StudyInstanceUid, this.SeriesInstanceUid, this.SopInstanceUid, frameNumber); // return DicomFileLoader.LoadFramePixelData(args); //} #endregion private bool IsStoredTag(uint tag) { var dicomTag = DicomTagDictionary.GetDicomTag(tag); return(dicomTag != null && IsStoredTag(dicomTag)); }
/// <summary> /// Evaluate /// </summary> /// <param name="arg"></param> /// <returns></returns> public override object Evaluate(object arg) { if (string.IsNullOrEmpty(Text)) { return(null); } if (Text.StartsWith("$")) { var msg = arg as DicomMessageBase; var collection = arg as DicomAttributeCollection; if (collection == null && msg == null) { return(null); } DicomTag tag = DicomTagDictionary.GetDicomTag(Text.Substring(1)); if (tag == null) { throw new NoSuchDicomTagException(Text.Substring(1)); } if (msg != null) { if (msg.DataSet.Contains(tag)) { collection = msg.DataSet; } else if (msg.MetaInfo.Contains(tag)) { collection = msg.MetaInfo; } } if (collection == null) { return(null); } DicomAttribute attrib; if (collection.TryGetAttribute(tag, out attrib)) { if (attrib.IsEmpty || attrib.IsNull) { return(null); } if (attrib.Tag.VR.Equals(DicomVr.SLvr)) { return(attrib.GetInt32(0, 0)); } if (attrib.Tag.VR.Equals(DicomVr.SSvr)) { return(attrib.GetInt16(0, 0)); } if (attrib.Tag.VR.Equals(DicomVr.ATvr) || attrib.Tag.VR.Equals(DicomVr.ULvr)) { return(attrib.GetUInt32(0, 0)); } if (attrib.Tag.VR.Equals(DicomVr.DSvr) || attrib.Tag.VR.Equals(DicomVr.FDvr)) { return(attrib.GetFloat64(0, 0f)); } if (attrib.Tag.VR.Equals(DicomVr.FLvr)) { return(attrib.GetFloat32(0, 0f)); } if (attrib.Tag.VR.Equals(DicomVr.ISvr)) { return(attrib.GetInt64(0, 0)); } if (attrib.Tag.VR.Equals(DicomVr.USvr)) { return(attrib.GetUInt16(0, 0)); } if (attrib.Tag.VR.Equals(DicomVr.SLvr)) { return(attrib.GetInt32(0, 0)); } if (attrib.Tag.VR.Equals(DicomVr.OBvr) || attrib.Tag.VR.Equals(DicomVr.OWvr) || attrib.Tag.VR.Equals(DicomVr.OFvr)) { return(attrib.StreamLength.ToString(CultureInfo.InvariantCulture)); } return(attrib.ToString().Trim()); } return(null); } return(Text); }
private static void AssertAreEqual(IDicomAttributeProvider expectedDataSource, IDicomAttributeProvider actualDataSource, uint dicomTag, string message = "", params object[] args) { var tag = DicomTagDictionary.GetDicomTag(dicomTag); Assert.AreEqual(expectedDataSource[dicomTag], actualDataSource[dicomTag], "@{1}: {0}", string.Format(message, args), tag != null ? tag.Name : dicomTag.ToString("X8")); }