public void UpdateDicomFile(UpdateData updateData) { DicomFileFormat dicomFile = new DicomFileFormat(); dicomFile.Load(updateData.DicomFileName, DicomReadOptions.DeferLoadingLargeElements); foreach (KeyValuePair <DicomTag, string> kvp in updateData.UpdateDataset) { dicomFile.Dataset.SetString(kvp.Key, kvp.Value); } foreach (KeyValuePair <DicomTag, string> kvp in updateData.UpdateMetadata) { dicomFile.FileMetaInfo.SetString(kvp.Key, kvp.Value); } dicomFile.Dataset.PreloadDeferredBuffers(); dicomFile.Save(updateData.DicomFileName, DicomWriteOptions.Default); //if (updateData.DicomFileName != null) //{ // string path = Path.GetDirectoryName(updateData.DicomFilePath); // File.Move(updateData.DicomFilePath, path + @"\" + updateData.DicomFileName); //} }
/// <summary>Creates DICOM image object from file</summary> /// <param name="fileName">Source file</param> public DicomImage(string fileName) { DicomFileFormat ff = new DicomFileFormat(); ff.Load(fileName, DicomReadOptions.Default); Load(ff.Dataset); }
public void UpdateDicomFile(string updateFile, string dicomTag, string newValue) { try { DicomFileFormat dicomFile = new DicomFileFormat(); DicomTag updateDicomTag = DicomTag.Parse(dicomTag); dicomFile.Load(updateFile, DicomReadOptions.DeferLoadingLargeElements); string what = updateDicomTag.Entry.ToString(); if (updateDicomTag.Entry.ToString().StartsWith("0002")) { dicomFile.FileMetaInfo.SetString(updateDicomTag, newValue); } else { dicomFile.Dataset.SetString(updateDicomTag, newValue); } dicomFile.Dataset.PreloadDeferredBuffers(); dicomFile.Save(updateFile, DicomWriteOptions.Default); } catch (Exception e) { MessageBox.Show(e.ToString()); } }
private void OnClickPixelDataMD5(object sender, EventArgs e) { if (_selected == -1) { return; } try { DicomFileFormat ff = new DicomFileFormat(); ff.Load(_files[_selected], DicomReadOptions.Default | DicomReadOptions.KeepGroupLengths | DicomReadOptions.DeferLoadingLargeElements | DicomReadOptions.DeferLoadingPixelData); DcmPixelData pixels = new DcmPixelData(ff.Dataset); if (pixels.NumberOfFrames == 0) { MessageBox.Show(this, "No pixel data", "Pixel Data MD5"); } else if (pixels.NumberOfFrames >= 1) { MessageBox.Show(this, pixels.ComputeMD5(), String.Format("Pixel Data MD5 [{0} frames]", pixels.NumberOfFrames)); } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } catch { } }
private void OnClickSaveWithTransferSyntax(object sender, EventArgs e) { if (_selected == -1) { return; } TransferSyntaxForm tsForm = new TransferSyntaxForm(); if (tsForm.ShowDialog(this) == DialogResult.OK) { SaveFileDialog sfd = new SaveFileDialog(); sfd.RestoreDirectory = true; if (sfd.ShowDialog(this) == DialogResult.OK) { DicomFileFormat ff = new DicomFileFormat(); ff.Load(_files[_selected], DicomReadOptions.Default); if (tsForm.SelectedTransferSyntax != null) { ff.ChangeTransferSyntax(tsForm.SelectedTransferSyntax, null); } ff.Save(sfd.FileName, DicomWriteOptions.Default); } } }
internal CStoreRequestResult Send(CStoreClient client) { Load(client); if (HasError) { if (client.Associate.FindAbstractSyntax(SOPClassUID) == 0) { client.Reassociate(); return(CStoreRequestResult.Reassociate); } } if (client.OnCStoreRequestBegin != null) { client.OnCStoreRequestBegin(client, this); } if (HasError) { Status = DcmStatus.UnrecognizedOperation; if (client.OnCStoreRequestFailed != null) { client.OnCStoreRequestFailed(client, this); } return(CStoreRequestResult.Failure); } byte pcid = client.Associate.FindAbstractSyntaxWithTransferSyntax(SOPClassUID, TransferSyntax); if (pcid == 0) { client.Log.Info("{0} -> C-Store request failed: No accepted presentation context for {1}", client.LogID, SOPClassUID.Description); Status = DcmStatus.SOPClassNotSupported; if (client.OnCStoreRequestFailed != null) { client.OnCStoreRequestFailed(client, this); } return(CStoreRequestResult.Failure); } if (_dataset != null) { client.SendCStoreRequest(pcid, SOPInstanceUID, _dataset); } else { using (Stream s = DicomFileFormat.GetDatasetStream(FileName)) { client.SendCStoreRequest(pcid, SOPInstanceUID, s); s.Close(); } } if (client.OnCStoreRequestComplete != null) { client.OnCStoreRequestComplete(client, this); } return(CStoreRequestResult.Success); }
public CStoreRequestInfo(string fileName, object userModel) { try { _fileName = fileName; if (!File.Exists(fileName)) { throw new FileNotFoundException("Unable to load DICOM file!", fileName); } DicomTag stopTag = (userModel != null) ? DicomTags.PixelData : DcmFileMetaInfo.StopTag; DicomFileFormat ff = new DicomFileFormat(); ff.Load(fileName, stopTag, DicomReadOptions.Default); _transferSyntax = ff.FileMetaInfo.TransferSyntax; _originalTransferSyntax = _transferSyntax; _sopClass = ff.FileMetaInfo.MediaStorageSOPClassUID; _sopInst = ff.FileMetaInfo.MediaStorageSOPInstanceUID; if (userModel != null) { ff.Dataset.LoadDicomFields(userModel); _userState = userModel; } _status = DcmStatus.Pending; } catch (Exception e) { _status = DcmStatus.ProcessingFailure; _exception = e; throw; } }
private void UpdateImageBox(DcmImageBox imageBox, String filename, int index) { //try //{ var ff = new DicomFileFormat(); ff.Load(filename, DicomReadOptions.DefaultWithoutDeferredLoading); if (ff.Dataset == null) { return; } ff.Dataset.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian, null); var pixelData = new DcmPixelData(ff.Dataset); var pi = PhotometricInterpretation.Lookup(pixelData.PhotometricInterpretation); // Grayscale only printer? if (pi.IsColor && _supportsColorPrinting == false) { pixelData.Unload(); return; } // Color only printer? if (pi.IsColor == false && _supportsGrayscalePrinting == false) { pixelData.Unload(); return; } DicomUID imageBoxSOPClassUID; DcmItemSequence seq; var item = new DcmItemSequenceItem(); pixelData.UpdateDataset(item.Dataset); if (pi.IsColor) { imageBoxSOPClassUID = DicomUID.BasicColorImageBoxSOPClass; seq = new DcmItemSequence(DicomTags.BasicColorImageSequence); } else { imageBoxSOPClassUID = DicomUID.BasicGrayscaleImageBoxSOPClass; seq = new DcmItemSequence(DicomTags.BasicGrayscaleImageSequence); } seq.AddSequenceItem(item); imageBox.Dataset.AddItem(seq); pixelData.Unload(); imageBox.UpdateImageBox(imageBoxSOPClassUID); imageBox.ImageBoxPosition = (ushort)index; //} //catch (Exception) //{ //} }
private TreeModel LoadFileFormat(DicomFileFormat ff) { TreeModel model = new TreeModel(); LoadDataset(ff.FileMetaInfo, model.Nodes); LoadDataset(ff.Dataset, model.Nodes); return(model); }
private int getSeriesNumberFromDcm(string dcmFile) { int seriesNumber; DicomFileFormat fileRead = new DicomFileFormat(); fileRead.Load(dcmFile, DicomReadOptions.DeferLoadingLargeElements); seriesNumber = Convert.ToInt32(fileRead.Dataset.GetValueString(new DicomTag(DicomConstTags.SeriesNumber))); fileRead = null; return(seriesNumber); }
//extract identifier(UID) from file private String getIdentifier(FileStream fs) { String identifier = String.Empty; try { DicomFileFormat dff = new DicomFileFormat(); dff.Load(fs, DicomReadOptions.Default); identifier = dff.Dataset.GetValueString(DicomTags.SOPInstanceUID); } catch (Exception e) { Console.WriteLine(e); } return(identifier); }
/// <summary> /// Asynchronously read DICOM file object. /// </summary> /// <param name="source">Byte source to read.</param> /// <param name="fileMetaInfo">Reader observer for file meta information.</param> /// <param name="dataset">Reader observer for dataset.</param> /// <param name="stop">Stop criterion in dataset.</param> /// <returns>Awaitable reader result.</returns> public async Task <DicomReaderResult> ReadAsync( IByteSource source, IDicomReaderObserver fileMetaInfo, IDicomReaderObserver dataset, Func <ParseState, bool> stop = null) { var parse = await ParseAsync(source, fileMetaInfo, dataset, stop).ConfigureAwait(false); lock (this.locker) { this.fileFormat = parse.Item2; this.syntax = parse.Item3; } return(parse.Item1); }
/// <summary> /// Read DICOM file object. /// </summary> /// <param name="source">Byte source to read.</param> /// <param name="fileMetaInfo">Reader observer for file meta information.</param> /// <param name="dataset">Reader observer for dataset.</param> /// <param name="stop">Stop criterion in dataset.</param> /// <returns>Reader result.</returns> public DicomReaderResult Read( IByteSource source, IDicomReaderObserver fileMetaInfo, IDicomReaderObserver dataset, Func <ParseState, bool> stop = null) { var parse = Parse(source, fileMetaInfo, dataset, stop); lock (this.locker) { this.fileFormat = parse.Item2; this.syntax = parse.Item3; } return(parse.Item1); }
public List <Dictionary <string, string> > getDicomElementInfo(string fileName, string dirPath) { try { DicomFileFormat dff = new DicomFileFormat(); List <Dictionary <string, string> > elements = new List <Dictionary <string, string> >(); string loadPath = dirPath + "\\" + fileName; dff.Load(loadPath, DicomReadOptions.DeferLoadingLargeElements); foreach (DcmItem di in dff.Dataset.Elements) { Dictionary <string, string> elementData = new Dictionary <string, string>(); elementData.Add("Name", di.Name.ToString()); elementData.Add("Tag", di.Tag.ToString()); if (dff.Dataset.GetValueString(di.Tag) != "") { elementData.Add("Value", dff.Dataset.GetValueString(di.Tag)); } else { elementData.Add("Value", "--Null--"); } elements.Add(elementData); } foreach (DcmItem di in dff.FileMetaInfo.Elements) { Dictionary <string, string> elementData = new Dictionary <string, string>(); elementData.Add("Name", di.Name.ToString()); elementData.Add("Tag", di.Tag.ToString()); if (dff.FileMetaInfo.GetValueString(di.Tag) != "") { elementData.Add("Value", dff.FileMetaInfo.GetValueString(di.Tag)); } else { elementData.Add("Value", "--Null--"); } elements.Add(elementData); } return(elements); } catch (Exception e) { string error = e.ToString(); return(null); } }
private void LoadButtonClick(object sender, RoutedEventArgs e) { OpenFileDialog dlg = Resources["dicomFileDialog"] as OpenFileDialog; if (dlg != null && dlg.ShowDialog().GetValueOrDefault()) { using (var memStream = new MemoryStream()) { using (var fileStream = dlg.OpenFile()) { fileStream.CopyTo(memStream); } var ff = new DicomFileFormat(); ff.Load(memStream, DicomReadOptions.Default); DumpDisplayDataset(dlg.FileName, ff.Dataset); } } }
private void ExtractMetaData(FileStream fs, DicomInfo dicom) { DicomFileFormat dff = new DicomFileFormat(); dff.Load(fs, DicomReadOptions.Default); dicom.patientName = dff.Dataset.GetValueString(DicomTags.PatientsName); dicom.studyUID = dff.Dataset.GetValueString(DicomTags.StudyInstanceUID); dicom.seriesUID = dff.Dataset.GetValueString(DicomTags.SeriesInstanceUID); dicom.imageUID = dff.Dataset.GetValueString(DicomTags.SOPInstanceUID); dicom.sex = dff.Dataset.GetValueString(DicomTags.PatientsSex); dicom.pBday = dff.Dataset.GetValueString(DicomTags.PatientsBirthDate); dicom.age = dff.Dataset.GetValueString(DicomTags.PatientsAge); dicom.imgNumber = dff.Dataset.GetValueString(DicomTags.InstanceNumber); dicom.modality = dff.Dataset.GetValueString(DicomTags.Modality); dicom.bodyPart = dff.Dataset.GetValueString(DicomTags.BodyPartExamined); dicom.studyDesc = dff.Dataset.GetValueString(DicomTags.StudyDescription); dicom.seriesDesc = dff.Dataset.GetValueString(DicomTags.SeriesDescription); dicom.sliceThickness = dff.Dataset.GetValueString(DicomTags.SliceThickness); }
private static void CheckDICOMFile(FileInfo FI, TextWriter output, List <DicomTag> DicomTagsToCheck, Dictionary <DicomTag, List <String> > tagTovalues) { //output.WriteLine("Checking: " + FI.FullName); var dcmFile = new DicomFileFormat(); var dcmFileName = FI.FullName; if (dcmFile.Load(dcmFileName, DicomReadOptions.Default) == DicomReadStatus.Success) { var sb = new StringBuilder(); if (dcmFile.Dataset != null) { foreach (var DT in DicomTagsToCheck) { var Element = dcmFile.Dataset.GetElement(DT); if (Element != null) { var ElementValue = Element.GetValueString(); if (ElementValue != null && ElementValue.Length != 0) { //output.WriteLine(Element + " = " + ElementValue); addValue(tagTovalues, DT, ElementValue); } } } } else { Console.WriteLine("dcm2txt: Missing dataset in DICOM file '{0}'.", dcmFileName); return; } //output.WriteLine(sb.ToString()); } else { Console.WriteLine("dcm2txt: '{0}' does not appear to be a DICOM file.", dcmFileName); return; } }
private void fileNameButton_Click(object sender, RoutedEventArgs e) { OpenFileDialog dlg = Resources["dicomFileDialog"] as OpenFileDialog; if (dlg != null && dlg.ShowDialog().GetValueOrDefault()) { using (var memStream = new MemoryStream()) { using (var fileStream = dlg.File.OpenRead()) { fileStream.CopyTo(memStream); } DicomFileFormat ff = new DicomFileFormat(); ff.Load(memStream, DicomReadOptions.Default); if (ff.Dataset != null) { StringBuilder sb = new StringBuilder(); ff.Dataset.Dump(sb, String.Empty, DicomDumpOptions.Default); RawDump = sb.ToString(); var xmlDoc = XDicom.ToXML(ff.Dataset, XDicomOptions.None); var txtWriter = new StringWriter(); xmlDoc.Save(txtWriter); XmlDump = txtWriter.ToString(); DicomImage = ff.Dataset.Contains(DicomTags.PixelData) ? GetImageSource(ff.Dataset) : null; } else { RawDump = XmlDump = String.Format(Resources["noDicomFileDataMsg"].ToString(), dlg.File.Name); DicomImage = null; } } UpdateLog(); } }
private bool LoadFile(string file) { bool success = false; DicomFileFormat ff = new DicomFileFormat(); try { ClearDump(); ff.Load(file, DicomReadOptions.Default | DicomReadOptions.KeepGroupLengths); success = true; } catch (Exception e) { MessageBox.Show(e.Message + "\n\n" + file, "Error parsing file!", MessageBoxButtons.OK, MessageBoxIcon.Error); } treeDump.Model = LoadFileFormat(ff); treeDump.ExpandAll(); if (success) { if (ff.Dataset.Contains(DicomTags.PixelData)) { tsbViewImage.Enabled = true; tsbExtractPixels.Enabled = true; tsbPixelDataMD5.Enabled = true; } tsbSaveTS.Enabled = true; } else { tsbViewImage.Enabled = false; tsbExtractPixels.Enabled = false; tsbSaveTS.Enabled = false; tsbPixelDataMD5.Enabled = false; } return(success); }
private static void UpdateFileFormatAndSyntax( string code, string uid, ref DicomFileFormat fileFormat, ref DicomTransferSyntax syntax) { if (code != null) { if (code == "ACR-NEMA 1.0") { fileFormat = DicomFileFormat.ACRNEMA1; } else if (code == "ACR-NEMA 2.0") { fileFormat = DicomFileFormat.ACRNEMA2; } } if (uid != null) { syntax = DicomTransferSyntax.Parse(uid); } }
private void OnClickExtractPixels(object sender, EventArgs e) { if (_selected == -1) { return; } try { DicomFileFormat ff = new DicomFileFormat(); ff.Load(_files[_selected], DicomReadOptions.Default | DicomReadOptions.KeepGroupLengths | DicomReadOptions.DeferLoadingLargeElements | DicomReadOptions.DeferLoadingPixelData); DcmPixelData pixels = new DcmPixelData(ff.Dataset); if (pixels.NumberOfFrames == 0) { return; } else if (pixels.NumberOfFrames >= 1) { SaveFileDialog sfd = new SaveFileDialog(); sfd.RestoreDirectory = true; if (sfd.ShowDialog(this) == DialogResult.OK) { byte[] data = pixels.GetFrameDataU8(0); File.WriteAllBytes(sfd.FileName, data); } } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } catch { } }
static void Test(string relativePath) { try { using (var stream = OpenRead(relativePath)) { var input = new BufferedStreamReader(stream); if (DicomFileFormat.TryReadHeader(input, out DicomFileMetaInformation fileMetaInformation)) { Console.WriteLine($"SOPClassUID = {fileMetaInformation.MediaStorageSOPClassUID}"); Console.WriteLine($"TransferSyntax = {(DicomUID)fileMetaInformation.TransferSyntaxUID}"); Console.WriteLine(JsonSerializer.Serialize(fileMetaInformation, new JsonSerializerOptions { WriteIndented = true })); var xmlOutputPath = $"{stream.Name}.xml"; Console.WriteLine($"Writing dataset to {xmlOutputPath}"); var dataSet = new XElement("DicomDataSet"); dataSet.SetAttributeValue("Source", stream.Name); var dataSetReader = DicomStreamReader.Create(input, fileMetaInformation.TransferSyntaxUID); dataSetReader.ReadDataSet(dataSet, new DicomToXmlConverter()); dataSet.Save(xmlOutputPath); } else { Console.WriteLine($"Skipped"); } } } catch (Exception error) { Console.WriteLine($"ERROR: {error.Message}"); } }
private static void Preprocess( IByteSource source, ref DicomFileFormat fileFormat, ref DicomTransferSyntax syntax) { // mark file origin source.Mark(); // test for DICM preamble source.Skip(128); if (source.GetUInt8() == 'D' && source.GetUInt8() == 'I' && source.GetUInt8() == 'C' && source.GetUInt8() == 'M') { fileFormat = DicomFileFormat.DICOM3; } // test for incorrect syntax in file meta info do { if (fileFormat == DicomFileFormat.DICOM3) { // move milestone to after preamble source.Mark(); } else { // rewind to origin milestone source.Rewind(); } // test for file meta info var group = source.GetUInt16(); if (@group > 0x00ff) { source.Endian = Endian.Big; syntax = DicomTransferSyntax.ExplicitVRBigEndian; @group = Endian.Swap(@group); } if (@group > 0x00ff) { // invalid starting tag fileFormat = DicomFileFormat.Unknown; source.Rewind(); break; } if (fileFormat == DicomFileFormat.Unknown) { fileFormat = @group == 0x0002 ? DicomFileFormat.DICOM3NoPreamble : DicomFileFormat.DICOM3NoFileMetaInfo; } var element = source.GetUInt16(); var tag = new DicomTag(@group, element); // test for explicit VR var vrt = Encoding.UTF8.GetBytes(tag.DictionaryEntry.ValueRepresentations[0].Code); var vrs = source.GetBytes(2); if (vrt[0] != vrs[0] || vrt[1] != vrs[1]) { // implicit VR syntax = syntax.Endian == Endian.Little ? DicomTransferSyntax.ImplicitVRLittleEndian : DicomTransferSyntax.ImplicitVRBigEndian; } source.Rewind(); }while (fileFormat == DicomFileFormat.Unknown); if (fileFormat == DicomFileFormat.Unknown) { throw new DicomReaderException("Attempted to read invalid DICOM file"); } // Adopt transfer syntax endianess to byte source. source.Endian = syntax.Endian; }
public DicomFileReader() { _reader = new DicomReader(); _fileFormat = DicomFileFormat.Unknown; _syntax = DicomTransferSyntax.ExplicitVRLittleEndian; }
/// <summary> /// Initializes a new instance of <see cref="DicomFileReader"/>. /// </summary> public DicomFileReader() { this.fileFormat = DicomFileFormat.Unknown; this.syntax = null; this.locker = new object(); }
private void ParsePreamble(IByteSource source, object state) { try { if (!source.Require(132, ParsePreamble, state)) return; // mark file origin _source.Mark(); // test for DICM preamble _source.Skip(128); if (_source.GetUInt8() == 'D' && _source.GetUInt8() == 'I' && _source.GetUInt8() == 'C' && _source.GetUInt8() == 'M') _fileFormat = DicomFileFormat.DICOM3; // test for incorrect syntax in file meta info do { if (_fileFormat == DicomFileFormat.DICOM3) { // move milestone to after preamble _source.Mark(); } else { // rewind to origin milestone _source.Rewind(); } // test for file meta info var group = _source.GetUInt16(); if (group > 0x00ff) { _source.Endian = Endian.Big; _syntax = DicomTransferSyntax.ExplicitVRBigEndian; group = Endian.Swap(group); } if (group > 0x00ff) { // invalid starting tag _fileFormat = DicomFileFormat.Unknown; _source.Rewind(); break; } if (_fileFormat == DicomFileFormat.Unknown) { if (group == 0x0002) _fileFormat = DicomFileFormat.DICOM3NoPreamble; else _fileFormat = DicomFileFormat.DICOM3NoFileMetaInfo; } var element = _source.GetUInt16(); var tag = new DicomTag(group, element); // test for explicit VR var vrt = Encoding.UTF8.GetBytes(tag.DictionaryEntry.ValueRepresentations[0].Code); var vrs = _source.GetBytes(2); if (vrt[0] != vrs[0] || vrt[1] != vrs[1]) { // implicit VR if (_syntax.Endian == Endian.Little) _syntax = DicomTransferSyntax.ImplicitVRLittleEndian; else _syntax = DicomTransferSyntax.ImplicitVRBigEndian; } _source.Rewind(); } while (_fileFormat == DicomFileFormat.Unknown); if (_fileFormat == DicomFileFormat.Unknown) throw new DicomReaderException("Attempted to read invalid DICOM file"); var obs = new DicomReaderCallbackObserver(); if (_fileFormat != DicomFileFormat.DICOM3) { obs.Add(DicomTag.RecognitionCodeRETIRED, (object sender, DicomReaderEventArgs ea) => { try { string code = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length); if (code == "ACR-NEMA 1.0") _fileFormat = DicomFileFormat.ACRNEMA1; else if (code == "ACR-NEMA 2.0") _fileFormat = DicomFileFormat.ACRNEMA2; } catch { } }); } obs.Add(DicomTag.TransferSyntaxUID, (object sender, DicomReaderEventArgs ea) => { try { string uid = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length); _syntax = DicomTransferSyntax.Parse(uid); } catch { } }); _source.Endian = _syntax.Endian; _reader.IsExplicitVR = _syntax.IsExplicitVR; if (_fileFormat == DicomFileFormat.DICOM3NoFileMetaInfo) _reader.BeginRead(_source, new DicomReaderMultiObserver(obs, _dataObserver), null, OnDatasetParseComplete, null); else _reader.BeginRead(_source, new DicomReaderMultiObserver(obs, _fmiObserver), FileMetaInfoStopTag, OnFileMetaInfoParseComplete, null); } catch (Exception e) { if (_exception == null) _exception = e; _result = DicomReaderResult.Error; } finally { if (_result != DicomReaderResult.Processing && _result != DicomReaderResult.Suspended) { _async.Set(); } } }
private void ParsePreamble(IByteSource source, object state) { try { if (!source.Require(132, ParsePreamble, state)) { return; } // mark file origin _source.Mark(); // test for DICM preamble _source.Skip(128); if (_source.GetUInt8() == 'D' && _source.GetUInt8() == 'I' && _source.GetUInt8() == 'C' && _source.GetUInt8() == 'M') { _fileFormat = DicomFileFormat.DICOM3; } // test for incorrect syntax in file meta info do { if (_fileFormat == DicomFileFormat.DICOM3) { // move milestone to after preamble _source.Mark(); } else { // rewind to origin milestone _source.Rewind(); } // test for file meta info var group = _source.GetUInt16(); if (group > 0x00ff) { _source.Endian = Endian.Big; _syntax = DicomTransferSyntax.ExplicitVRBigEndian; group = Endian.Swap(group); } if (group > 0x00ff) { // invalid starting tag _fileFormat = DicomFileFormat.Unknown; _source.Rewind(); break; } if (_fileFormat == DicomFileFormat.Unknown) { if (group == 0x0002) { _fileFormat = DicomFileFormat.DICOM3NoPreamble; } else { _fileFormat = DicomFileFormat.DICOM3NoFileMetaInfo; } } var element = _source.GetUInt16(); var tag = new DicomTag(group, element); // test for explicit VR var vrt = Encoding.ASCII.GetBytes(tag.DictionaryEntry.ValueRepresentations[0].Code); var vrs = _source.GetBytes(2); if (vrt[0] != vrs[0] || vrt[1] != vrs[1]) { // implicit VR if (_syntax.Endian == Endian.Little) { _syntax = DicomTransferSyntax.ImplicitVRLittleEndian; } else { _syntax = DicomTransferSyntax.ImplicitVRBigEndian; } } _source.Rewind(); } while (_fileFormat == DicomFileFormat.Unknown); if (_fileFormat == DicomFileFormat.Unknown) { throw new DicomReaderException("Attempted to read invalid DICOM file"); } var obs = new DicomReaderCallbackObserver(); if (_fileFormat != DicomFileFormat.DICOM3) { obs.Add(DicomTag.RecognitionCodeRETIRED, (object sender, DicomReaderEventArgs ea) => { try { string code = Encoding.ASCII.GetString(ea.Data.Data); if (code == "ACR-NEMA 1.0") { _fileFormat = DicomFileFormat.ACRNEMA1; } else if (code == "ACR-NEMA 2.0") { _fileFormat = DicomFileFormat.ACRNEMA2; } } catch { } }); } obs.Add(DicomTag.TransferSyntaxUID, (object sender, DicomReaderEventArgs ea) => { try { string uid = Encoding.ASCII.GetString(ea.Data.Data); _syntax = DicomTransferSyntax.Parse(uid); } catch { } }); _source.Endian = _syntax.Endian; _reader.IsExplicitVR = _syntax.IsExplicitVR; if (_fileFormat == DicomFileFormat.DICOM3NoFileMetaInfo) { _reader.BeginRead(_source, new DicomReaderMultiObserver(obs, _dataObserver), null, OnDatasetParseComplete, null); } else { _reader.BeginRead(_source, new DicomReaderMultiObserver(obs, _fmiObserver), FileMetaInfoStopTag, OnFileMetaInfoParseComplete, null); } } catch (Exception e) { if (_exception == null) { _exception = e; } _result = DicomReaderResult.Error; } finally { if (_result != DicomReaderResult.Processing && _result != DicomReaderResult.Suspended) { _async.Set(); } } }
public string MakeGreyDicom(byte[] greybytes, ushort imgwidth, ushort imgheight) { DcmUID studyUid = DcmUID.Generate(); DcmUID seriesUid = DcmUID.Generate(studyUid, 1); DcmUID instUid = DcmUID.Generate(seriesUid, 1); DcmDataset data = new DcmDataset(DcmTS.ExplicitVRBigEndian); //.ImplicitVRLittleEndian ok data.AddElementWithValue(DcmTags.SOPClassUID, DcmUIDs.CTImageStorage); //ComputedRadiographyImageStorage ok //data.AddElementWithValue(DcmTags.SOPClassUID, DcmUIDs .SecondaryCapture); data.AddElementWithValue(DcmTags.StudyInstanceUID, studyUid); data.AddElementWithValue(DcmTags.SeriesInstanceUID, seriesUid); data.AddElementWithValue(DcmTags.SOPInstanceUID, instUid);//"1.3.6.1.4.1.30071.6.635719267134010719.1.1" //data.AddElementWithValue(DcmTags.MediaStorageSOPClassUID, DcmUIDs.ImplicitVRLittleEndian); //data.AddElementWithValueString(DcmTags.MediaStorageSOPClassUID, DcmUIDs.ComputedRadiographyImageStorage.ToString()); //type 2 attributes ////data.AddElement(DcmTags.PrinterStatus); if (tags.ContainsKey("0010,0020")) { data.AddElementWithValueString(DcmTags.PatientID, tags["0010,0020"].Substring(5)); } if (tags.ContainsKey("0010,0010")) { data.AddElementWithValueString(DcmTags.PatientsName, tags["0010,0010"].Substring(5)); } if (tags.ContainsKey("0010,0030")) { data.AddElementWithValueString(DcmTags.PatientsBirthDate, tags["0010,0030"].Substring(5)); } if (tags.ContainsKey("0010,0040")) { data.AddElementWithValueString(DcmTags.PatientsSex, tags["0010,0040"].Substring(5)); } if (tags.ContainsKey("0010,1010")) { data.AddElementWithValueString(DcmTags.PatientsAge, tags["0010,1010"].Substring(5)); } if (tags.ContainsKey("0008,0005")) { data.AddElementWithValueString(DcmTags.SpecificCharacterSet, tags["0008,0005"].Substring(5)); } if (tags.ContainsKey("0008,0008")) { data.AddElementWithValueString(DcmTags.ImageType, tags["0008,0008"].Substring(5)); } //if (tags.ContainsKey("0008,0016")) // data.AddElementWithValueString(DcmTags.ContentTime, DateTime.Now.ToString()); //if (tags.ContainsKey("0008,0018")) // data.AddElementWithValueString(DcmTags.ContentTime, DateTime.Now.ToString()); if (tags.ContainsKey("0008,0020")) { data.AddElementWithValueString(DcmTags.StudyDate, tags["0008,0020"].Substring(5)); } if (tags.ContainsKey("0008,0021")) { data.AddElementWithValueString(DcmTags.SeriesDate, tags["0008,0021"].Substring(5)); } if (tags.ContainsKey("0008,0022")) { data.AddElementWithValueString(DcmTags.AcquisitionDate, tags["0008,0022"].Substring(5)); } if (tags.ContainsKey("0008,0023")) { data.AddElementWithValueString(DcmTags.ContentDate, tags["0008,0023"].Substring(5)); } if (tags.ContainsKey("0008,002a")) { data.AddElementWithValueString(DcmTags.AcquisitionDateTime, tags["0008,002a"].Substring(5)); } if (tags.ContainsKey("0008,0030")) { data.AddElementWithValueString(DcmTags.StudyTime, tags["0008,0030"].Substring(5)); } if (tags.ContainsKey("0008,0031")) { data.AddElementWithValueString(DcmTags.SeriesTime, tags["0008,0031"].Substring(5)); } if (tags.ContainsKey("0008,0032")) { data.AddElementWithValueString(DcmTags.AcquisitionTime, tags["0008,0032"].Substring(5)); } if (tags.ContainsKey("0008,0033")) { data.AddElementWithValueString(DcmTags.ContentTime, tags["0008,0033"].Substring(5)); } if (tags.ContainsKey("0008,0050")) { data.AddElementWithValueString(DcmTags.AcquisitionNumber, tags["0008,0050"].Substring(5)); } if (tags.ContainsKey("0008,0060")) { data.AddElementWithValueString(DcmTags.Modality, tags["0008,0060"].Substring(5)); } if (tags.ContainsKey("0008,0070")) { data.AddElementWithValueString(DcmTags.Manufacturer, tags["0008,0070"].Substring(5)); } if (tags.ContainsKey("0008,0080")) { data.AddElementWithValueString(DcmTags.InstitutionName, tags["0008,0080"].Substring(5)); } if (tags.ContainsKey("0008,0081")) { data.AddElementWithValueString(DcmTags.InstitutionAddress, tags["0008,0081"].Substring(5)); } if (tags.ContainsKey("0008,0090")) { data.AddElementWithValueString(DcmTags.ReferringPhysiciansName, tags["0008,0090"].Substring(5)); } if (tags.ContainsKey("0008,1010")) { data.AddElementWithValueString(DcmTags.StationName, tags["0008,1010"].Substring(5)); } if (tags.ContainsKey("0008,1030")) { data.AddElementWithValueString(DcmTags.StudyDescription, tags["0008,1030"].Substring(5)); } if (tags.ContainsKey("0008,103e")) { data.AddElementWithValueString(DcmTags.SeriesDescription, tags["0008,103e"].Substring(5)); } if (tags.ContainsKey("0008,1090")) { data.AddElementWithValueString(DcmTags.ManufacturersModelName, tags["0008,1090"].Substring(5)); } if (tags.ContainsKey("0018,0010")) { data.AddElementWithValueString(DcmTags.ContrastBolusAgent, tags["0018,0010"].Substring(5)); } if (tags.ContainsKey("0018,0015")) { data.AddElementWithValueString(DcmTags.BodyPartExamined, tags["0018,0015"].Substring(5)); } if (tags.ContainsKey("0018,0050")) { data.AddElementWithValueString(DcmTags.SliceThickness, tags["0018,0050"].Substring(5)); } if (tags.ContainsKey("0018,0060")) { data.AddElementWithValueString(DcmTags.KVP, tags["0018,0060"].Substring(5)); } if (tags.ContainsKey("0018,0090")) { data.AddElementWithValueString(DcmTags.DataCollectionDiameter, tags["0018,0090"].Substring(5)); } if (tags.ContainsKey("0018,1000")) { data.AddElementWithValueString(DcmTags.DeviceSerialNumber, tags["0018,1000"].Substring(5)); } if (tags.ContainsKey("0018,1020")) { data.AddElementWithValueString(DcmTags.SoftwareVersions, tags["0018,1020"].Substring(5)); } if (tags.ContainsKey("0018,1030")) { data.AddElementWithValueString(DcmTags.ProtocolName, tags["0018,1030"].Substring(5)); } if (tags.ContainsKey("0018,1041")) { data.AddElementWithValueString(DcmTags.ContrastBolusVolume, tags["0018,1041"].Substring(5)); } if (tags.ContainsKey("0018,1042")) { data.AddElementWithValueString(DcmTags.ContrastBolusStartTime, tags["0018,1042"].Substring(5)); } if (tags.ContainsKey("0018,1043")) { data.AddElementWithValueString(DcmTags.ContrastBolusStopTime, tags["0018,1043"].Substring(5)); } if (tags.ContainsKey("0018,1044")) { data.AddElementWithValueString(DcmTags.ContrastBolusTotalDose, tags["0018,1044"].Substring(5)); } if (tags.ContainsKey("0018,1046")) { data.AddElementWithValueString(DcmTags.ContrastFlowRate, tags["0018,1046"].Substring(5)); } if (tags.ContainsKey("0018,1047")) { data.AddElementWithValueString(DcmTags.ContrastFlowDuration, tags["0018,1047"].Substring(5)); } if (tags.ContainsKey("0018,1049")) { data.AddElementWithValueString(DcmTags.ContrastBolusIngredientConcentration, tags["0018,1049"].Substring(5)); } if (tags.ContainsKey("0018,1100")) { data.AddElementWithValueString(DcmTags.ReconstructionDiameter, tags["0018,1100"].Substring(5)); } if (tags.ContainsKey("0018,1110")) { data.AddElementWithValueString(DcmTags.DistanceSourceToDetector, tags["0018,1110"].Substring(5)); } if (tags.ContainsKey("0018,1111")) { data.AddElementWithValueString(DcmTags.DistanceSourceToPatient, tags["0018,1111"].Substring(5)); } if (tags.ContainsKey("0018,1120")) { data.AddElementWithValueString(DcmTags.GantryDetectorTilt, tags["0018,1120"].Substring(5)); } if (tags.ContainsKey("0018,1130")) { data.AddElementWithValueString(DcmTags.TableHeight, tags["0018,1130"].Substring(5)); } if (tags.ContainsKey("0018,1140")) { data.AddElementWithValueString(DcmTags.RotationDirection, tags["0018,1140"].Substring(5)); } if (tags.ContainsKey("0018,1150")) { data.AddElementWithValueString(DcmTags.ExposureTime, tags["0018,1150"].Substring(5)); } if (tags.ContainsKey("0018,1151")) { data.AddElementWithValueString(DcmTags.XRayTubeCurrent, tags["0018,1151"].Substring(5)); } if (tags.ContainsKey("0018,1152")) { data.AddElementWithValueString(DcmTags.Exposure, tags["0018,1152"].Substring(5)); } if (tags.ContainsKey("0018,1160")) { data.AddElementWithValueString(DcmTags.FilterType, tags["0018,1160"].Substring(5)); } if (tags.ContainsKey("0018,1170")) { data.AddElementWithValueString(DcmTags.GeneratorPower, tags["0018,1170"].Substring(5)); } if (tags.ContainsKey("0018,1190")) { data.AddElementWithValueString(DcmTags.FocalSpots, tags["0018,1190"].Substring(5)); } if (tags.ContainsKey("0018,1200")) { data.AddElementWithValueString(DcmTags.DateOfLastCalibration, tags["0018,1200"].Substring(5)); } if (tags.ContainsKey("0018,1201")) { data.AddElementWithValueString(DcmTags.TimeOfLastCalibration, tags["0018,1201"].Substring(5)); } if (tags.ContainsKey("0018,1210")) { data.AddElementWithValueString(DcmTags.ConvolutionKernel, tags["0018,1210"].Substring(5)); } if (tags.ContainsKey("0018,5100")) { data.AddElementWithValueString(DcmTags.PatientPosition, tags["0018,5100"].Substring(5)); } //if (tags.ContainsKey("0020,000D")) // data.AddElementWithValueString(DcmTags.ContrastBolusStopTime, DateTime.Now.ToString()); //if (tags.ContainsKey("0020,000E")) // data.AddElementWithValueString(DcmTags.ContrastBolusStopTime, DateTime.Now.ToString()); if (tags.ContainsKey("0020,0010")) { data.AddElementWithValueString(DcmTags.StudyID, tags["0020,0010"].Substring(5)); } if (tags.ContainsKey("0020,0011")) { data.AddElementWithValueString(DcmTags.SeriesNumber, tags["0020,0011"].Substring(5)); } if (tags.ContainsKey("0020,0012")) { data.AddElementWithValueString(DcmTags.AccessionNumber, tags["0020,0012"].Substring(5)); } if (tags.ContainsKey("0020,0013")) { data.AddElementWithValueString(DcmTags.InstanceNumber, tags["0020,0013"].Substring(5)); } if (tags.ContainsKey("0020,0032")) { data.AddElementWithValueString(DcmTags.ImagePositionPatient, tags["0020,0032"].Substring(5)); } if (tags.ContainsKey("0020,0037")) { data.AddElementWithValueString(DcmTags.ImageOrientationPatient, tags["0020,0037"].Substring(5)); } if (tags.ContainsKey("0020,0052")) { data.AddElementWithValueString(DcmTags.FrameOfReferenceUID, tags["0020,0052"].Substring(5)); } if (tags.ContainsKey("0020,1040")) { data.AddElementWithValueString(DcmTags.PositionReferenceIndicator, tags["0020,1040"].Substring(5)); } if (tags.ContainsKey("0020,1041")) { data.AddElementWithValueString(DcmTags.SliceLocation, tags["0020,1041"].Substring(5)); } if (tags.ContainsKey("0020,4000")) { data.AddElementWithValueString(DcmTags.ImageComments, tags["0020,4000"].Substring(5)); } //data.AddElementWithValueString(DcmTags.StudyTime, DateTime.Now.ToString()); //data.AddElementWithValueString(DcmTags.AccessionNumber, ""); //data.AddElementWithValueString(DcmTags.ReferringPhysiciansName, ""); //data.AddElementWithValueString(DcmTags.StudyID, "1"); //data.AddElementWithValueString(DcmTags.SeriesNumber, "1"); //data.AddElementWithValueString(DcmTags.ModalitiesInStudy, "CT");//CR //data.AddElementWithValueString(DcmTags.Modality, "CT");//CR //data.AddElementWithValueString(DcmTags.NumberOfStudyRelatedInstances, "1"); //data.AddElementWithValueString(DcmTags.NumberOfStudyRelatedSeries, "1"); //data.AddElementWithValueString(DcmTags.NumberOfSeriesRelatedInstances, "1"); //data.AddElementWithValueString(DcmTags.PatientOrientation, "HFS");//F/A //data.AddElementWithValueString(DcmTags.ImageLaterality, "U"); if (tags.ContainsKey("0028,1050")) { data.AddElementWithValueString(DcmTags.WindowCenter, "1113"); } if (tags.ContainsKey("0028,1051")) { data.AddElementWithValueString(DcmTags.WindowWidth, "749"); } //data.AddElementWithValueString(DcmTags.WindowCenterWidthExplanation, "WINDOW1\\WINDOW2"); data.AddElementWithValueString(DcmTags.PixelRepresentation, "0"); data.AddElementWithValueString(DcmTags.RescaleIntercept, "0");//0 data.AddElementWithValueString(DcmTags.RescaleSlope, "1"); //data.AddElementWithValueString(DcmTags.RotationDirection, "CW"); //ushort bitdepth = 2;未使用过 DcmPixelData pixelData = new DcmPixelData(DcmTS.ImplicitVRLittleEndian); pixelData.PixelRepresentation = 0;//ok pixelData.ImageWidth = imgwidth; pixelData.ImageHeight = imgheight; pixelData.SamplesPerPixel = 1; //ok pixelData.HighBit = 15; //ok pixelData.BitsStored = 16; //ok pixelData.BitsAllocated = 16; //ok //pixelData.SamplesPerPixel = 1; //pixelData.HighBit = 7; //pixelData.BitsStored = 8; //pixelData.BitsAllocated = 8; pixelData.ImageType = "ORIGINAL\\PRIMARY\\AXIAL"; pixelData.PhotometricInterpretation = "MONOCHROME2";//2 byte gray? //ok //pixelData.FragmentSize //pixelData.IsLossy = true; //pixelData.LossyCompressionMethod = "01"; pixelData.PixelDataElement = DcmElement.Create(DcmTags.PixelData, DcmVR.OW); //OB: Other Byte, OW: Other Word //pixelData.AddFrame(bmpBytes); pixelData.AddFrame(greybytes); pixelData.UpdateDataset(data); DicomFileFormat ff = new DicomFileFormat(data); //string fileout = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "greyimg_test.dcm"); ff.Save(fileout, Dicom.DicomWriteOptions.Default);//Default ff = null; return(fileout); }
private static async Task<Tuple<DicomReaderResult, DicomFileFormat, DicomTransferSyntax>> DoParseAsync( IByteSource source, IDicomReaderObserver fileMetasetInfoObserver, IDicomReaderObserver datasetObserver, Func<ParseState, bool> stop, DicomTransferSyntax syntax, DicomFileFormat fileFormat) { string code = null, uid = null; var obs = new DicomReaderCallbackObserver(); if (fileFormat != DicomFileFormat.DICOM3) { obs.Add( DicomTag.RecognitionCodeRETIRED, (sender, ea) => { try { code = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length); } catch { } }); } obs.Add( DicomTag.TransferSyntaxUID, (sender, ea) => { try { uid = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length); } catch { } }); var reader = new DicomReader { IsExplicitVR = syntax.IsExplicitVR, IsDeflated = false }; DicomReaderResult result; if (fileFormat == DicomFileFormat.DICOM3NoFileMetaInfo) { result = await reader.ReadAsync(source, new DicomReaderMultiObserver(obs, datasetObserver), stop).ConfigureAwait(false); UpdateFileFormatAndSyntax(code, uid, ref fileFormat, ref syntax); } else { if ( await reader.ReadAsync( source, new DicomReaderMultiObserver(obs, fileMetasetInfoObserver), FileMetaInfoStopCriterion).ConfigureAwait(false) != DicomReaderResult.Stopped) { throw new DicomReaderException("DICOM File Meta Info ended prematurely"); } UpdateFileFormatAndSyntax(code, uid, ref fileFormat, ref syntax); // rewind to last marker (start of previous tag)... ugly because // it requires knowledge of how the parser is implemented source.Rewind(); source.Endian = syntax.Endian; reader.IsExplicitVR = syntax.IsExplicitVR; reader.IsDeflated = syntax.IsDeflate; result = await reader.ReadAsync(source, datasetObserver, stop).ConfigureAwait(false); } return Tuple.Create(result, fileFormat, syntax); }
public ParseResult(DicomReaderResult result, DicomFileFormat format, DicomTransferSyntax syntax) { Result = result; Format = format; Syntax = syntax; }
private static async Task <Tuple <DicomReaderResult, DicomFileFormat, DicomTransferSyntax> > DoParseAsync( IByteSource source, IDicomReaderObserver fileMetasetInfoObserver, IDicomReaderObserver datasetObserver, Func <ParseState, bool> stop, DicomTransferSyntax syntax, DicomFileFormat fileFormat) { string code = null, uid = null; var obs = new DicomReaderCallbackObserver(); if (fileFormat != DicomFileFormat.DICOM3) { obs.Add( DicomTag.RecognitionCodeRETIRED, (sender, ea) => { try { code = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length); } catch { } }); } obs.Add( DicomTag.TransferSyntaxUID, (sender, ea) => { try { uid = Encoding.UTF8.GetString(ea.Data.Data, 0, ea.Data.Data.Length); } catch { } }); var reader = new DicomReader { IsExplicitVR = syntax.IsExplicitVR, IsDeflated = false }; DicomReaderResult result; if (fileFormat == DicomFileFormat.DICOM3NoFileMetaInfo) { result = await reader.ReadAsync(source, new DicomReaderMultiObserver(obs, datasetObserver), stop).ConfigureAwait(false); UpdateFileFormatAndSyntax(code, uid, ref fileFormat, ref syntax); } else { if ( await reader.ReadAsync( source, new DicomReaderMultiObserver(obs, fileMetasetInfoObserver), _FileMetaInfoStopCriterion).ConfigureAwait(false) != DicomReaderResult.Stopped) { throw new DicomReaderException("DICOM File Meta Info ended prematurely"); } UpdateFileFormatAndSyntax(code, uid, ref fileFormat, ref syntax); // rewind to last marker (start of previous tag)... ugly because // it requires knowledge of how the parser is implemented source.Rewind(); source.Endian = syntax.Endian; reader.IsExplicitVR = syntax.IsExplicitVR; reader.IsDeflated = syntax.IsDeflate; result = await reader.ReadAsync(source, datasetObserver, stop).ConfigureAwait(false); } return(Tuple.Create(result, fileFormat, syntax)); }
/// <summary> /// Asynchronously read DICOM file object. /// </summary> /// <param name="source">Byte source to read.</param> /// <param name="fileMetaInfo">Reader observer for file meta information.</param> /// <param name="dataset">Reader observer for dataset.</param> /// <param name="stop">Stop criterion in dataset.</param> /// <returns>Awaitable reader result.</returns> public async Task<DicomReaderResult> ReadAsync( IByteSource source, IDicomReaderObserver fileMetaInfo, IDicomReaderObserver dataset, Func<ParseState, bool> stop = null) { var parse = await ParseAsync(source, fileMetaInfo, dataset, stop).ConfigureAwait(false); lock (this.locker) { this.fileFormat = parse.Item2; this.syntax = parse.Item3; } return parse.Item1; }
/// <summary> /// Loads the DICOM file and changes the transfer syntax if needed. (Internal) /// </summary> /// <param name="client">C-Store Client</param> public void Load(CStoreClient client) { if (_loaded) { return; } try { DicomTransferSyntax tx = null; foreach (DcmPresContext pc in client.Associate.GetPresentationContexts()) { if (pc.Result == DcmPresContextResult.Accept && pc.AbstractSyntax == _sopClass) { tx = pc.AcceptedTransferSyntax; break; } } if (tx == null) { throw new DicomNetworkException("No accepted presentation contexts for abstract syntax: " + _sopClass.Description); } // Possible to stream from file? if (!client.DisableFileStreaming && tx == TransferSyntax) { using (FileStream fs = DicomFileFormat.GetDatasetStream(_fileName)) { _datasetSize = Convert.ToUInt32(fs.Length - fs.Position); fs.Close(); } return; } DcmCodecParameters codecParams = null; if (tx == client.PreferredTransferSyntax) { codecParams = client.PreferredTransferSyntaxParams; } DicomFileFormat ff = new DicomFileFormat(); ff.Load(FileName, DicomReadOptions.DefaultWithoutDeferredLoading); if (_originalTransferSyntax != tx) { if (_originalTransferSyntax.IsEncapsulated) { // Dataset is compressed... decompress try { ff.ChangeTransferSytnax(DicomTransferSyntax.ExplicitVRLittleEndian, null); } catch { client.Log.Error("{0} -> Unable to change transfer syntax:\n\tclass: {1}\n\told: {2}\n\tnew: {3}\n\treason: {4}\n\tcodecs: {5} - {6}", client.LogID, SOPClassUID.Description, _originalTransferSyntax, DicomTransferSyntax.ExplicitVRLittleEndian, #if DEBUG HasError ? "Unknown" : Error.ToString(), #else HasError ? "Unknown" : Error.Message, #endif DicomCodec.HasCodec(_originalTransferSyntax), DicomCodec.HasCodec(DicomTransferSyntax.ExplicitVRLittleEndian)); throw; } } if (tx.IsEncapsulated) { // Dataset needs to be compressed try { ff.ChangeTransferSytnax(tx, codecParams); } catch { client.Log.Error("{0} -> Unable to change transfer syntax:\n\tclass: {1}\n\told: {2}\n\tnew: {3}\n\treason: {4}\n\tcodecs: {5} - {6}", client.LogID, SOPClassUID.Description, ff.Dataset.InternalTransferSyntax, tx, #if DEBUG HasError ? "Unknown" : Error.ToString(), #else HasError ? "Unknown" : Error.Message, #endif DicomCodec.HasCodec(ff.Dataset.InternalTransferSyntax), DicomCodec.HasCodec(tx)); throw; } } } _dataset = ff.Dataset; _datasetSize = _dataset.CalculateWriteLength(tx, DicomWriteOptions.Default); _transferSyntax = tx; } catch (Exception e) { _dataset = null; _transferSyntax = _originalTransferSyntax; _status = DcmStatus.ProcessingFailure; _exception = e; } finally { _loaded = true; } }
/// <summary> /// Read DICOM file object. /// </summary> /// <param name="source">Byte source to read.</param> /// <param name="fileMetaInfo">Reader observer for file meta information.</param> /// <param name="dataset">Reader observer for dataset.</param> /// <param name="stop">Stop criterion in dataset.</param> /// <returns>Reader result.</returns> public DicomReaderResult Read( IByteSource source, IDicomReaderObserver fileMetaInfo, IDicomReaderObserver dataset, Func<ParseState, bool> stop = null) { var parse = Parse(source, fileMetaInfo, dataset, stop); lock (this.locker) { this.fileFormat = parse.Format; this.syntax = parse.Syntax; } return parse.Result; }
public ParseResult(DicomReaderResult result, DicomFileFormat format, DicomTransferSyntax syntax) { this.Result = result; this.Format = format; this.Syntax = syntax; }
private static void Preprocess( IByteSource source, ref DicomFileFormat fileFormat, ref DicomTransferSyntax syntax) { // mark file origin source.Mark(); // test for DICM preamble source.Skip(128); if (source.GetUInt8() == 'D' && source.GetUInt8() == 'I' && source.GetUInt8() == 'C' && source.GetUInt8() == 'M') { fileFormat = DicomFileFormat.DICOM3; } // test for incorrect syntax in file meta info do { if (fileFormat == DicomFileFormat.DICOM3) { // move milestone to after preamble source.Mark(); } else { // rewind to origin milestone source.Rewind(); } // test for file meta info var group = source.GetUInt16(); if (@group > 0x00ff) { source.Endian = Endian.Big; syntax = DicomTransferSyntax.ExplicitVRBigEndian; @group = Endian.Swap(@group); } if (@group > 0x00ff) { // invalid starting tag fileFormat = DicomFileFormat.Unknown; source.Rewind(); break; } if (fileFormat == DicomFileFormat.Unknown) { fileFormat = @group == 0x0002 ? DicomFileFormat.DICOM3NoPreamble : DicomFileFormat.DICOM3NoFileMetaInfo; } var element = source.GetUInt16(); var tag = new DicomTag(@group, element); // test for explicit VR var vrt = Encoding.UTF8.GetBytes(tag.DictionaryEntry.ValueRepresentations[0].Code); var vrs = source.GetBytes(2); if (vrt[0] != vrs[0] || vrt[1] != vrs[1]) { // implicit VR syntax = syntax.Endian == Endian.Little ? DicomTransferSyntax.ImplicitVRLittleEndian : DicomTransferSyntax.ImplicitVRBigEndian; } source.Rewind(); } while (fileFormat == DicomFileFormat.Unknown); if (fileFormat == DicomFileFormat.Unknown) { throw new DicomReaderException("Attempted to read invalid DICOM file"); } // Adopt transfer syntax endianess to byte source. source.Endian = syntax.Endian; }