public void Initialise(DicomFile dcmFile, String filePath)
        {
            _filePath = filePath;
              DicomFile file = null;

              file = dcmFile;
              _UpdateInfo(file);

              try
            {
            string[] filePaths = Directory.GetFiles(@_filePath);

            ThreadPool.QueueUserWorkItem(delegate(object s)
              {
                foreach (string filename in filePaths)
                  {
                  var image = new DicomImage(filename);
                  this.Dispatcher.BeginInvoke(new WaitCallback(_DisplayImage), image);
                  _numOfRow = _numOfRow + 1;
                  }
              });
            }
              catch (DicomFileException ex)
            {
            file = ex.File;
            MessageBox.Show(this, "Exception while loading DICOM file: " + ex.Message, "Error loading DICOM file");
            }
        }
 private static byte[] SerializeDicom_(DicomDataset dataset)
 {
     var stream = new MemoryStream();
     var file = new DicomFile(dataset);
     file.Save(stream);
     return stream.ToArray();
 }
		public static DicomFile Clone(this DicomFile original) {
			var df = new DicomFile();
			df.FileMetaInfo.Add(original.FileMetaInfo);
			df.Dataset.Add(original.Dataset);
			df.Dataset.InternalTransferSyntax = original.Dataset.InternalTransferSyntax;
			return df;
		}
Beispiel #4
0
 public void Save_ToFile_FileExistsOnDisk()
 {
     var saveFile = new DicomFile(MinimumDatatset);
     var fileName = Path.GetTempFileName();
     saveFile.Save(fileName);
     Assert.True(File.Exists(fileName));
 }
Beispiel #5
0
 public async Task SaveAsync_ToFile_FileExistsOnDisk()
 {
     var saveFile = new DicomFile(MinimumDatatset);
     var fileName = Path.GetTempFileName();
     await saveFile.SaveAsync(fileName);
     Assert.True(File.Exists(fileName));
 }
        public virtual IEnumerable <ObjectRetrieveResult> GetTransformedSopInstances
        (
            IObjectId query,
            string fromMediaType,
            string fromTransferSyntax,
            string toMediaType,
            string toTransferSyntax
        )
        {
            var fromMediaProp = new DicomMediaProperties(fromMediaType, fromTransferSyntax);
            var fromMediaID   = MediaFactory.Create(query, fromMediaProp);
            var frameList     = (null != query.Frame) ? new int[] { query.Frame.Value } : null;


            if (StorageService.Exists(fromMediaID))
            {
                foreach (IStorageLocation location in StorageService.EnumerateLocation(fromMediaID))
                {
                    fo.DicomFile defaultFile = fo.DicomFile.Open(location.GetReadStream( ));

                    foreach (var transformedLocation in  TransformDataset(defaultFile.Dataset, toMediaType, toTransferSyntax, frameList))
                    {
                        yield return(new ObjectRetrieveResult(transformedLocation, toTransferSyntax));
                    }
                }
            }
        }
Beispiel #7
0
        public void ConvertToJson()
        {
            var testDir = Path.Combine(TestDirPath, "convertToJson");
            JsonDicomConverter jsonConverter = new JsonDicomConverter( );

            Directory.CreateDirectory(testDir);

            foreach (string file in Directory.GetFiles(DicomHelpers.GetSampleImagesFolder( )))
            {
                string          fullPath = Path.Combine(testDir, Path.GetFileName(file));
                fo.DicomDataset sourceDS = fo.DicomFile.Open(file).Dataset;

                jsonConverter.WriteInlineBinary = true;

                string sourceJsonDicom = jsonConverter.Convert(sourceDS);

                System.IO.File.WriteAllText(fullPath + ".jsn", sourceJsonDicom);


                fo.DicomDataset targetDs = jsonConverter.Convert(sourceJsonDicom);

                var dsF = new fo.DicomFile(targetDs);

                dsF.Save(fullPath + ".jsn.dcm");

                string destJsonDicom = jsonConverter.Convert(targetDs);

                System.IO.File.WriteAllText(fullPath + ".gen.jsn", destJsonDicom);

                Assert.AreEqual(sourceJsonDicom, destJsonDicom);
            }
        }
Beispiel #8
0
        private void ReadAndDisplayDicomFile(string fileName, string fileNameOnly)
        {
            file = DicomFile.Open(fileName);
            foreach (var tag in file.Dataset)
            {
                string str = ($"{tag}|{file.Dataset.GetValueOrDefault(tag.Tag, 0, "")}");
                fileTags.Add(str);
            }
            IImage image    = new DicomImage(fileName).RenderImage();
            var    dicomimg = new DicomImage(fileName);

            label_size.Text = dicomimg.Height.ToString() + "x" + dicomimg.Width.ToString() + " pixel";
            dicomimg.Scale  = 1;

            Bitmap bmp     = image.AsSharedBitmap();
            Size   newSize = new Size((int)(dicomimg.Width * 2), (int)(dicomimg.Height * 2));

            bmp = new Bitmap(bmp, newSize);
            this.pictureBox1.Image = bmp;

            trackBar.Minimum       = 1;
            trackBar.Maximum       = 6;
            trackBar.SmallChange   = 1;
            trackBar.LargeChange   = 1;
            trackBar.UseWaitCursor = false;

            this.DoubleBuffered = true;
            org       = new PictureBox();
            org.Image = pictureBox1.Image;

            SetString();
        }
Beispiel #9
0
        private void DoSearch(string directoryToSearch)
        {
            IEnumerable <string> filenames = new List <string>();

            try
            {
                filenames = Directory.EnumerateFiles(directoryToSearch, "*.dcm", SearchOption.AllDirectories);
            }
            catch (DirectoryNotFoundException)
            {
                string errorMsg = $"Error: directory {directoryToSearch} not found.";
                UpdateStatus(lblStatusMessage, StatusCode.Error, errorMsg);
                return;
            }

            Dicom.DicomTag tag1 = tagInput1.Get();
            Dicom.DicomTag tag2 = tagInput2.Get();
            Dicom.DicomTag tag3 = tagInput3.Get();
            foreach (string filename in filenames)
            {
                //TODO!~ Use OpenAsync instead of Open.
                //TODO!+ If the file is not a DICOM file, DicomFile.Open (and DicomFile.OpenAsync) throws an Exception.
                // We catch that Exception. But if we're using Async, we should add  a "finally" to deal with this.

                try
                {
                    Dicom.DicomFile dicomFile = Dicom.DicomFile.Open(filename, Dicom.FileReadOption.Default); //TODO?~ Make sure we ONLY read the tags! Dicom.FileReadOption comes in here.

                    bool noTagsSpecified = (tag1 == null && tag2 == null && tag3 == null);

                    bool tag1Present = tag1 != null && dicomFile.Dataset.Contains(tag1);
                    bool tag2Present = tag2 != null && dicomFile.Dataset.Contains(tag2);
                    bool tag3Present = tag3 != null && dicomFile.Dataset.Contains(tag3);

                    //TODO!+ Adding stuff for finding a file based on SOP Class UID - DICOM Tag (0008,0016).
                    //TODO!~ Use the Tag's Value Representation to determine the type of the returned value.
                    if (tag1 != null)
                    {
                        object val1 = dicomFile.Dataset.GetValue <object>(tag1, 0);
                    }

                    if (noTagsSpecified || tag1Present || tag2Present || tag3Present)
                    {
                        tbSearchResults.Invoke((MethodInvoker) delegate
                        {
                            tbSearchResults.Text += (filename + Environment.NewLine);
                        });
                    }
                }
                catch (DicomFileException)
                {
                    string errMsg = $"Error: tried to open a file that was not a DICOM file.";
                    UpdateStatus(lblStatusMessage, StatusCode.Error, errMsg);
                }
            }
        }
Beispiel #10
0
        public fo.DicomDataset Convert(string xmlDcm)
        {
            fo.DicomDataset ds       = new fo.DicomDataset( );
            XDocument       document = XDocument.Parse(xmlDcm);

            ReadChildren(ds, document.Root, 0);

            fo.DicomFile df = new fo.DicomFile(ds);

            return(ds);
        }
Beispiel #11
0
        public void BeginOpen_FromFile_YieldsValidDicomFile()
        {
            var saveFile = new DicomFile(MinimumDatatset);
            var fileName = Path.GetTempFileName();
            saveFile.Save(fileName);

            var openFile = DicomFile.EndOpen(DicomFile.BeginOpen(fileName, null, null));
            var expected = MinimumDatasetInstanceUid;
            var actual = openFile.Dataset.Get<string>(DicomTag.SOPInstanceUID);
            Assert.Equal(expected, actual);
        }
 public void OpenFile(string fileName)
 {
     try
     {
         file = DicomFile.Open(fileName);
     }
     catch (DicomFileException ex)
     {
         file = ex.File;
     }
 }
Beispiel #13
0
        protected override WadoResponse DoProcess(IWadoUriRequest request, string mimeType)
        {
            fo.DicomFile df       = fo.DicomFile.Open(Location.GetReadStream( ));//TODO: check how the toolkit loads the image in memory or not. we do not need to load it
            WadoResponse response = new WadoResponse( );


            //df.Load ( Location.GetReadStream ( ), null, DicomReadOptions.DoNotStorePixelDataInDataSet);

            response.Content  = GenerateStreamFromString(df.ToString( ));
            response.MimeType = mimeType;

            return(response);
        }
        protected override void Upload(fo.DicomDataset dicomDataset, int frame, IStorageLocation location)
        {
            fo.DicomFile df = new fo.DicomFile(dicomDataset);


            using (Stream stream = new MemoryStream())
            {
                df.Save(stream);
                stream.Position = 0;

                location.Upload(stream);
            }
        }
        public RepoDicomFile(UploadFile file)
        {
            this.name = file.name;
            //file.data +=
            fileType = FileType.Dicom;

            //current conversion is: js UInt8Array -> js base64String -> c# string -> c# byte[] -> c# Stream
            //If a more direct conversion from js UInt8Array -> C# Stream is found, it should be used instead

            using (var ms = new MemoryStream(Encoding.Default.GetBytes(file.data))) {
                dicomFile = DicomFile.Open(ms);
            }
        }
Beispiel #16
0
        public void sendDicom(DicomFile file)
        {
            
            //adds dicom file to be sent with new request
            client.AddRequest(new DicomCStoreRequest(file));

            //send file to destination specified 
            try{
                client.Send(targetIP, port, useTLS, callingAE, calledAE);
            }
            catch(SocketException e){
                MessageBox.Show("Error: " + e.Message);
            }
        }
Beispiel #17
0
        public static IAsyncResult BeginOpen(string fileName, AsyncCallback callback, object state)
        {
            DicomFile df = new DicomFile();
            df.File = new FileReference(fileName);

            FileByteSource source = new FileByteSource(df.File);

            EventAsyncResult result = new EventAsyncResult(callback, state);

            DicomFileReader reader = new DicomFileReader();
            reader.BeginRead(source,
                new DicomDatasetReaderObserver(df.FileMetaInfo),
                new DicomDatasetReaderObserver(df.Dataset),
                OnReadComplete, new Tuple<DicomFileReader, DicomFile, EventAsyncResult>(reader, df, result));

            return result;
        }
Beispiel #18
0
        public void DicomFile_OpenUtf8Encoding_SwedishCharactersMaintained()
        {
            var expected = "Händer Å Fötter";
            var tag = DicomTag.DoseComment;

            var dataset = new DicomDataset(MinimumDatatset);
            dataset.Add(new DicomLongString(tag, DicomEncoding.GetEncoding("ISO IR 192"), expected));

            var outFile = new DicomFile(dataset);
            var stream = new MemoryStream();
            outFile.Save(stream);

            stream.Seek(0, SeekOrigin.Begin);
            var inFile = DicomFile.Open(stream, DicomEncoding.GetEncoding("ISO IR 192"));
            var actual = inFile.Dataset.Get<string>(tag);

            Assert.Equal(expected, actual);
        }
Beispiel #19
0
        public void DicomFile_OpenUtf8Encoding_SwedishCharactersMaintained()
        {
            var expected = "Händer Å Fötter";
            var tag = DicomTag.DoseComment;

            var dataset = new DicomDataset(
                new DicomUniqueIdentifier(DicomTag.SOPClassUID, DicomUID.RTDoseStorage),
                new DicomUniqueIdentifier(DicomTag.SOPInstanceUID, "1.2.3"),
                new DicomLongString(tag, DicomEncoding.GetEncoding("ISO IR 192"), expected));
            var outFile = new DicomFile(dataset);
            var stream = new MemoryStream();
            outFile.Save(stream);

            stream.Seek(0, SeekOrigin.Begin);
            var inFile = DicomFile.Open(stream, DicomEncoding.GetEncoding("ISO IR 192"));
            var actual = inFile.Dataset.Get<string>(tag);

            Assert.Equal(expected, actual);
        }
Beispiel #20
0
		private void OnClickSelect(object sender, EventArgs e) {
			DicomFile file1 = null;
			while (true) {
				var ofd = new OpenFileDialog();
				ofd.Title = "Choose first DICOM file";
				ofd.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";

				if (ofd.ShowDialog(this) == DialogResult.Cancel)
					return;

				try {
					file1 = DicomFile.Open(ofd.FileName);
					break;
				} catch (Exception ex) {
					MessageBox.Show(this, ex.Message, "Error opening DICOM file", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}

			DicomFile file2 = null;
			while (true) {
				var ofd = new OpenFileDialog();
				ofd.Title = "Choose second DICOM file";
				ofd.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";

				if (ofd.ShowDialog(this) == DialogResult.Cancel)
					return;

				try {
					file2 = DicomFile.Open(ofd.FileName);
					break;
				} catch (Exception ex) {
					MessageBox.Show(this, ex.Message, "Error opening DICOM file", MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}

			_file1 = file1;
			_file2 = file2;

			lblFile1.Text = _file1.File.Name;
			lblFile2.Text = _file2.File.Name;

			CompareFiles();
		}
Beispiel #21
0
        void dfs_FileFound(Dicom.Media.DicomFileScanner scanner, Dicom.DicomFile file, string fileName)
        {
            DicomDataset ds = file.Dataset;

            string modality = ds.Get <string>(DicomTag.Modality);

            // Console.WriteLine(string.Format("Found {0} {1}", modality, ds.Get<DicomUID>(DicomTag.SOPInstanceUID)));

            if (modality == null)
            {
                // handle this?
            }
            else if (modality.CompareTo("RTSTRUCT") == 0)
            {
                StoreStructureSet(ds);
            }
            else if (modality.CompareTo("RTPLAN") == 0)
            {
                // process plan
                Console.WriteLine("RTPLAN");
            }
            else if (modality.CompareTo("REG") == 0)
            {
                // process registration
                Console.WriteLine("REG");
            }
            else if (modality.CompareTo("RTRECORD") == 0)
            {
                // process RT RECORD
                Console.WriteLine("RTRECORD");
            }
            else if (modality.CompareTo("SR") == 0)
            {
                // process Structured Report
                Console.WriteLine("SR");
            }
            else
            {
                StoreImage(ds, modality);
            }
        }
Beispiel #22
0
		public void OpenFile(DicomFile file) {
			try {
				lvDicom.BeginUpdate();

				Reset();

				_file = file;

				new DicomDatasetWalker(_file.FileMetaInfo).Walk(new DumpWalker(this));
				new DicomDatasetWalker(_file.Dataset).Walk(new DumpWalker(this));

				if (_file.Dataset.Contains(DicomTag.PixelData))
					menuItemView.Enabled = true;
				menuItemSyntax.Enabled = true;
				menuItemSave.Enabled = true;
			} catch (Exception ex) {
				MessageBox.Show(this, "Exception while loading DICOM file: " + ex.Message, "Error loading DICOM file", MessageBoxButtons.OK, MessageBoxIcon.Error);
			} finally {
				lvDicom.EndUpdate();
			}
		}
		public DicomFileImage(string displayName, StorageFile storageFile, DicomFile dicomFile)
		{
			DisplayName = displayName;
			StorageFile = storageFile;
			DicomFile = dicomFile;

			var dataset = dicomFile.Dataset;
			if (dataset != null)
			{
				FirstFrameImage = dataset.Contains(DicomTag.PixelData)
					                  ? new DicomImage(dataset).RenderImageSource()
					                  : null;
				Modality = dataset.Get(DicomTag.Modality, String.Empty);
				NumberOfFrames = FirstFrameImage != null ? dataset.Get(DicomTag.NumberOfFrames, 1) : 0;
			}
			else
			{
				FirstFrameImage = null;
				Modality = String.Empty;
				NumberOfFrames = 0;
			}
		}
Beispiel #24
0
        public void ConvertToXml( )
        {
            var testDir      = Path.Combine(TestDirPath, "convertToXml");
            var xmlConverter = new XmlDicomConverter( )
            {
                WriteInlineBinary = true
            };


            Directory.CreateDirectory(testDir);
            //fo.DicomDataset sourceDS = Helper.GetDicomDataset ( 10 ).Clone ( fo.DicomTransferSyntax.ExplicitVRLittleEndian ) ;
            foreach (string file in Directory.GetFiles(DicomHelpers.GetSampleImagesFolder( )))
            {
                string          fullPath = Path.Combine(testDir, Path.GetFileName(file));
                fo.DicomDataset sourceDS = fo.DicomFile.Open(file).Dataset;


                var sourceXmlDicom = xmlConverter.Convert(sourceDS);

                System.IO.File.WriteAllText(fullPath + ".xml", sourceXmlDicom);

                fo.DicomDataset targetDs = xmlConverter.Convert(sourceXmlDicom);

                var dsF = new fo.DicomFile(targetDs);

                dsF.FileMetaInfo.TransferSyntax = fo.DicomTransferSyntax.Parse(targetDs.Get(fo.DicomTag.TransferSyntaxUID, targetDs.InternalTransferSyntax.ToString( )));

                dsF.Save(fullPath + ".gen.dcm");

                var destXmlDicom = xmlConverter.Convert(targetDs);

                System.IO.File.WriteAllText(fullPath + ".gen.xml", destXmlDicom);

                //private tags with private creator will cause this to fail
                //VR for OW change to OB
                Assert.AreEqual(sourceXmlDicom, destXmlDicom);
            }
        }
Beispiel #25
0
 public DicomFileException(DicomFile file, string message, Exception innerException)
     : base(message, innerException)
 {
     File = file;
 }
Beispiel #26
0
 public DicomFileException(DicomFile file, string format, params object[] args)
     : base(format, args)
 {
     File = file;
 }
Beispiel #27
0
		private void OnClickSave(object sender, EventArgs e) {
			var sfd = new SaveFileDialog();
			sfd.Filter = "DICOM (*.dcm)|*.dcm|Image (*.bmp;*.jpg;*.png;*.gif)|*.bmp;*.jpg;*.png;*.gif";

			if (sfd.ShowDialog() == DialogResult.Cancel)
				return;

			if (sfd.FilterIndex == 1) {
				var file = new DicomFile(_file.Dataset);
				file.Save(sfd.FileName);
			} else {
				var image = new DicomImage(_file.Dataset);
				image.RenderImage().Save(sfd.FileName);
			}
		}
Beispiel #28
0
		public DisplayForm(DicomFile file) {
			_file = file;
			InitializeComponent();
		}
Beispiel #29
0
        /// <summary>
        /// Asynchronously read a DICOM file from stream.
        /// </summary>
        /// <param name="stream">Stream to read.</param>
        /// <param name="fallbackEncoding">Encoding to use if encoding cannot be obtained from DICOM file.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns>Awaitable <see cref="DicomFile"/> instance.</returns>
        public static async Task<DicomFile> OpenAsync(Stream stream, Encoding fallbackEncoding, Func<ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException("fallbackEncoding");
            }
            var df = new DicomFile();

            try
            {
                var source = new StreamByteSource(stream);

                var reader = new DicomFileReader();
                var result =
                    await
                    reader.ReadAsync(
                        source,
                        new DicomDatasetReaderObserver(df.FileMetaInfo),
                        new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding),
                        stop).ConfigureAwait(false);

                if (result == DicomReaderResult.Processing)
                {
                    throw new DicomFileException(df, "Invalid read return state: {state}", result);
                }
                if (result == DicomReaderResult.Error)
                {
                    return null;
                }
                df.IsPartial = result == DicomReaderResult.Stopped || result == DicomReaderResult.Suspended;

                df.Format = reader.FileFormat;
                df.Dataset.InternalTransferSyntax = reader.Syntax;

                return df;
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Beispiel #30
0
        /// <summary>
        /// Reads the specified filename and returns a DicomFile object.  Note that the values for large
        /// DICOM elements (e.g. PixelData) are read in "on demand" to conserve memory.  Large DICOM elements
        /// are determined by their size in bytes - see the default value for this in the FileByteSource._largeObjectSize
        /// </summary>
        /// <param name="fileName">The filename of the DICOM file</param>
        /// <param name="fallbackEncoding">Encoding to apply when attribute Specific Character Set is not available.</param>
        /// <returns>DicomFile instance</returns>
        public static DicomFile Open(string fileName, Encoding fallbackEncoding) {
	        if (fallbackEncoding == null)
	        {
	            throw new ArgumentNullException("fallbackEncoding");
	        }
	        DicomFile df = new DicomFile();

			try {
				df.File = new FileReference(fileName);

				using (var source = new FileByteSource(df.File)) {
					DicomFileReader reader = new DicomFileReader();
					reader.Read(source,
						new DicomDatasetReaderObserver(df.FileMetaInfo),
						new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding));

					df.Format = reader.FileFormat;

					df.Dataset.InternalTransferSyntax = reader.Syntax;

					return df;
				}
			} catch (Exception e) {
				throw new DicomFileException(df, e.Message, e);
			}
		}
 private void _UpdateCaseInformation(DicomFile file)
 {
     txt_HdrPatientName.Text = file.Dataset.Get<string>(DicomTag.PatientName);
       txt_HdrPatientID.Text = file.Dataset.Get<string>(DicomTag.PatientID);
       txt_PatientAge.Text = file.Dataset.Get<string>(DicomTag.PatientAge);
       txt_PatientSex.Text = file.Dataset.Get<string>(DicomTag.PatientSex);
       txt_Institution.Text = file.Dataset.Get<string>(DicomTag.InstitutionName);
       txt_ScanDate.Text = file.Dataset.Get<string>(DicomTag.Date);
 }
Beispiel #32
0
        public static DicomFile Open(Stream stream)
        {
            var df = new DicomFile();

			try {
				var source = new StreamByteSource(stream);

				var reader = new DicomFileReader();
				reader.Read(source,
					new DicomDatasetReaderObserver(df.FileMetaInfo),
					new DicomDatasetReaderObserver(df.Dataset));

				df.Format = reader.FileFormat;

				df.Dataset.InternalTransferSyntax = reader.Syntax;

				return df;
			} catch (Exception e) {
				throw new DicomFileException(df, e.Message, e);
			}
        }
Beispiel #33
0
		public ReportForm(DicomFile file) {
			_file = file;
			InitializeComponent();
		}
Beispiel #34
0
        public async Task OpenAsync_FromFile_YieldsValidDicomFile()
        {
            var saveFile = new DicomFile(MinimumDatatset);
            var fileName = Path.GetTempFileName();
            saveFile.Save(fileName);

            var openFile = await DicomFile.OpenAsync(fileName);
            var expected = MinimumDatasetInstanceUid;
            var actual = openFile.Dataset.Get<string>(DicomTag.SOPInstanceUID);
            Assert.Equal(expected, actual);
        }
Beispiel #35
0
        public void Open_StreamOfMemoryMappedFile_YieldsValidDicomFile()
        {
            var saveFile = new DicomFile(MinimumDatatset);
            var fileName = Path.GetTempFileName();
            saveFile.Save(fileName);

            var file = MemoryMappedFile.CreateFromFile(fileName);
            var openFile = DicomFile.Open(file.CreateViewStream());
            var expected = MinimumDatasetInstanceUid;
            var actual = openFile.Dataset.Get<string>(DicomTag.SOPInstanceUID);
            Assert.Equal(expected, actual);
        }
Beispiel #36
0
 public DicomFileException(DicomFile file, string message)
     : base(message)
 {
     File = file;
 }
        private void OnClickLoadCase(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.FileName = "*.*"; // Default file name
            dlg.DefaultExt = ".*"; // Default file extension. Because sometimes DICOM = *.vtk, *.dcm, *.1...n, no standard.

            System.Windows.Forms.FolderBrowserDialog fb = new System.Windows.Forms.FolderBrowserDialog();
            fb.ShowDialog();

            try
              {
              BeginStoryboard((Storyboard)FindResource("rect_homeSB"));

                _filePath = fb.SelectedPath;
                DicomFile file = null;

                try
                  {
                  string[] filePaths = Directory.GetFiles(@_filePath);

                  file = DicomFile.Open(filePaths[0]); // terminator usually 1st or last of the series
                  dcmFile = file;
                  _UpdateCaseInformation(file);
                  var overviewImage = new DicomImage(filePaths[0]);
                  _DisplayOverviewImage(overviewImage);

                  //[fabhar - TODO] i know this is not a good pactice, but um..
                  //i cant think of something yet..

                  ThreadPool.QueueUserWorkItem(delegate(object s)
                  {
                  foreach (string filename in filePaths)
                    {
                    var image = new DicomImage(filename);
                    Directory.Delete("C:\\_MedData\\_MedTemp", true);
                    Directory.CreateDirectory("C:\\_MedData\\_MedTemp\\");

                    image.RenderImage().Save("C:\\_MedData\\_MedTemp\\"+_numOfRow+"IMG"+".jpg");
                    this.Dispatcher.Invoke(new WaitCallback(_DisplayImage), image);
                    _numOfRow = _numOfRow + 1;
                    }
                  });

                  //[fabhar] reference for future implementation of _DisplayImage() MT operation.

                  //Thread thread1 = new Thread(new ThreadStart(A));
                  //thread1.Start();
                  //thread1.Join();
                  }
                catch (DicomFileException ex)
                  {
                  file = ex.File;
                  MessageBox.Show(this, "Exception while loading DICOM file: " + ex.Message, "Error loading DICOM file");
                  }
            }
            catch (Exception ex)
              {
              MessageBox.Show(this, "Exception while loading DICOM file: " + ex.Message, "Error loading DICOM file");
              }
            finally
              {
              // end update here
              }
        }
        public void HasValidHeader_Part10File_ReturnsTrue()
        {
            var validHeader = DicomFile.HasValidHeader(@".\Test Data\CT1_J2KI");

            Assert.True(validHeader);
        }
 public static void EndSave(this DicomFile @this, IAsyncResult result)
 {
     AsyncFactory.ToEnd(result);
 }
Beispiel #40
0
 public DicomFileException(DicomFile file, string message)
     : base(message)
 {
     File = file;
 }
Beispiel #41
0
        /*This button loops through the already created xml file filled with
        * the tags to be anonymized. The list is populated with these specific
        * tags to be anonymized, and we then search through the DICOM file
        * and "remove" any information that corresponds to the information in the
        * list. This "removed" patient information is passed to the crosswalk
        table for later reference */
        private void Anonymize_Click(object sender, EventArgs e)
        {

            /*when an element in the taglist matches a tag in the
            dicom file, remove it from the dataset and add it to the crosswalk for later reference*/
            string filename = Filepath.Text;
            DicomFile file = DicomFile.Open(filename);
            DicomDataset dataSet = file.Dataset;

            path = "C:\\Users\\Tyler\\Documents\\Schoolwork\\Third Year\\COSC 310\\CrosswalkTable.txt";

            int i = 0;


            List<DicomTag> tags = new List<DicomTag>();
            
            foreach (string input in tagList)
            {                     

                foreach (DicomDictionaryEntry thing in DicomDictionary.Default)
                {
                    if (thing.Tag.ToString().Equals(input))
                    {
                        MessageBox.Show("found matching tag for " + thing.Tag.ToString());
                        tags.Add(thing.Tag);
                    }
                }
         
            }

            addPatientInfo(tags, dataSet, file.Dataset.Get<String>(DicomTag.PatientName));
        
            foreach (DicomTag thing in tags)
            {
                MessageBox.Show("anonymizing tag " + thing.ToString());
                dataSet.Remove(thing);
            }

            MessageBox.Show("writing new dicom file");
            DicomFile anon = new DicomFile(dataSet);
            try
            {
                anon.Save(@"anonymized" + i + ".dcm");
            }
            catch (Exception exc)
            {
                MessageBox.Show("Error: " + exc.ToString());
            }
        }
Beispiel #42
0
        public static DicomFile Open(Stream stream, Encoding fallbackEncoding)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException("fallbackEncoding");
            }
            var df = new DicomFile();

			try {
				var source = new StreamByteSource(stream);

				var reader = new DicomFileReader();
				reader.Read(source,
					new DicomDatasetReaderObserver(df.FileMetaInfo),
					new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding));

				df.Format = reader.FileFormat;

				df.Dataset.InternalTransferSyntax = reader.Syntax;

				return df;
			} catch (Exception e) {
				throw new DicomFileException(df, e.Message, e);
			}
        }
Beispiel #43
0
 public DicomFileException(DicomFile file, string message, Exception innerException)
     : base(message, innerException)
 {
     File = file;
 }
Beispiel #44
0
        /// <summary>
        /// Reads the specified file and returns a DicomFile object.  Note that the values for large
        /// DICOM elements (e.g. PixelData) are read in "on demand" to conserve memory.  Large DICOM elements
        /// are determined by their size in bytes - see the default value for this in the FileByteSource._largeObjectSize
        /// </summary>
        /// <param name="file">The file reference of the DICOM file</param>
        /// <param name="fallbackEncoding">Encoding to apply when attribute Specific Character Set is not available.</param>
        /// <returns>DicomFile instance</returns>
        internal static DicomFile Open(IFileReference file, Encoding fallbackEncoding)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException("fallbackEncoding");
            }
            DicomFile df = new DicomFile();

            try
            {
                df.File = file;

                using (var source = new FileByteSource(file))
                {
                    DicomFileReader reader = new DicomFileReader();
                    var result = reader.Read(
                        source,
                        new DicomDatasetReaderObserver(df.FileMetaInfo),
                        new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding));

                    if (result == DicomReaderResult.Processing)
                    {
                        throw new DicomFileException(df, "Invalid read return state: {state}", result);
                    }
                    if (result == DicomReaderResult.Error)
                    {
                        return null;
                    }
                    df.IsPartial = result == DicomReaderResult.Stopped || result == DicomReaderResult.Suspended;

                    df.Format = reader.FileFormat;

                    df.Dataset.InternalTransferSyntax = reader.Syntax;

                    return df;
                }
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Beispiel #45
0
 public DicomFileException(DicomFile file, string format, params object[] args)
     : base(format, args)
 {
     File = file;
 }