コード例 #1
0
ファイル: TestBase.cs プロジェクト: m-berkani/ClearCanvas
        protected Study CreateTestStudy1()
        {
            var studyUid = "1.2.3";
            var sops = base.SetupMRSeries(4, 5, studyUid);
            var xml = new StudyXml(studyUid);

            var seriesUids = new Dictionary<string, string>();
            var seriesModalities = new Dictionary<string, string>();
            var modalities = new[] { "MR", "MR", "SC", "KO" };

            foreach (var sop in sops)
            {
                //Make the UIDs constant.
                var seriesUid = sop[DicomTags.SeriesInstanceUid].ToString();
                if (!seriesUids.ContainsKey(seriesUid))
                {
                    seriesModalities[seriesUid] = modalities[seriesUids.Count];
                    seriesUids[seriesUid] = string.Format("1.2.3.{0}", seriesUids.Count + 1);
                }

                var modality = seriesModalities[seriesUid];
                seriesUid = seriesUids[seriesUid];

                sop[DicomTags.SeriesInstanceUid].SetString(0, seriesUid);
                sop[DicomTags.Modality].SetString(0, modality);

                var file = new DicomFile("", new DicomAttributeCollection(), sop);
                xml.AddFile(file);
            }

            var study = new Study();
            study.Update(xml);
            return study;
        }
コード例 #2
0
 public RemoveInstanceFromStudyXmlCommand(StudyStorageLocation location, StudyXml studyXml, DicomFile file)
     :base("Remove Instance From Study Xml", true)
 {
     _studyLocation = location;
     _file = file;
     _studyXml = studyXml;
 }
コード例 #3
0
ファイル: SetDicomTagTestBase.cs プロジェクト: nhannd/Xian
        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");
            
            Assert.IsTrue(cmd.Apply(file), "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);

        }
コード例 #4
0
        /// <summary>
        /// Run the decompressor.
        /// </summary>
        /// <param name="file"></param>
        public void Process(ClearCanvas.Dicom.DicomFile file)
        {
            var proposedTs = ClearCanvas.Dicom.TransferSyntax.GetTransferSyntax(OutputTransferSyntax);
            var currentTs  = file.TransferSyntax;

            ClearCanvas.Dicom.TransferSyntax finalTs = currentTs;

            if (proposedTs != TransferSyntax.ExplicitVrBigEndian &&
                proposedTs != TransferSyntax.ImplicitVrLittleEndian &&
                proposedTs != TransferSyntax.ExplicitVrLittleEndian)
            {
                log.Warn("Decompressor cannot supports target transfer syntax of EVBE, IVLE, EVLE only.  Using IVLE ..");
                finalTs = TransferSyntax.ImplicitVrLittleEndian;
            }
            else
            {
                finalTs = proposedTs;
            }

            log.Info(string.Format("Deompress: Proposed: {0}, current {1}, final {2}", proposedTs, currentTs, finalTs));

            if (currentTs != finalTs)
            {
                file.ChangeTransferSyntax(finalTs);
            }
        }
コード例 #5
0
ファイル: AIMG.cs プロジェクト: radiopaedia/uploader-agent
 public static void MultiFrameProcess(DbStudy study)
 {
     string dcmPath = ADCM.GetStoreString();
     var seriesList = Directory.GetDirectories(Path.Combine(dcmPath, study.study_uid));
     foreach (var sePath in seriesList)
     {
         var filesList = Directory.GetFiles(sePath, "*.dcm");
         if (filesList.Length < 2)
             continue;
         for (int i = 0; i < filesList.Length; i++)
         {
             var dcm = new DicomFile(filesList[i]);
             dcm.Load();
             int frameCount = dcm.DataSet[DicomTags.NumberOfFrames].GetInt16(0, 0);                
             if (frameCount > 1)
             {
                 string newSeriesUID = sePath + "." + i;
                 newSeriesUID = newSeriesUID.Substring(newSeriesUID.LastIndexOf(Path.DirectorySeparatorChar) + 1);
                 string newSeriesPath = Path.Combine(dcmPath, study.study_uid, newSeriesUID);
                 Directory.CreateDirectory(newSeriesPath);
                 string fileName = Path.GetFileName(filesList[i]);
                 string oldPath = filesList[i];
                 string newPath = Path.Combine(newSeriesPath, fileName);
                 File.Move(filesList[i], Path.Combine(newSeriesPath, fileName));
             }
         }                        
     }
     foreach (string sePath in seriesList)
     {
         var filesCount = Directory.GetFiles(sePath);
         if (filesCount.Length < 1)
             Directory.Delete(sePath);
     }
 }
コード例 #6
0
		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				_frame = null;
				_dicomFile = null;

				if (_imageSop != null)
				{
					_imageSop.Dispose();
					_imageSop = null;
				}

				if (_sopDataSource != null)
				{
					_sopDataSource.Dispose();
					_sopDataSource = null;
				}

				if (_filename != null)
				{
					if (File.Exists(_filename))
						File.Delete(_filename);
					_filename = null;
				}
			}
			base.Dispose(disposing);
		}
コード例 #7
0
ファイル: TestCompressionForm.cs プロジェクト: nhannd/Xian
        private void buttonCompress_Click(object sender, EventArgs e)
        {
            TransferSyntax syntax = this.comboBoxCompressionType.SelectedItem as TransferSyntax;
            if (syntax == null)
            {
                MessageBox.Show("Transfer syntax not selected");
                return;
            }

            DicomFile dicomFile = new DicomFile(textBoxSourceFile.Text);

            dicomFile.Load();
            if (dicomFile.TransferSyntax.Encapsulated)
            {
                MessageBox.Show(String.Format("Message encoded as {0}, cannot compress.", dicomFile.TransferSyntax));
                return;
            }

            dicomFile.Filename = textBoxDestinationFile.Text;

            dicomFile.ChangeTransferSyntax(syntax);

            dicomFile.Save();

        }
コード例 #8
0
        /// <summary>
        /// Updates the Patient's Name tag in the specified <see cref="DicomFile"/>
        /// based on the specified <see cref="StudyStorageLocation"/>. Normalization
        /// may occur.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public UpdateItem Apply(DicomFile file)
        {
            Platform.CheckForNullReference(file, "file");
            
            string orginalPatientsNameInFile = file.DataSet[DicomTags.PatientsName].ToString();

			// Note: only apply the name rules if we can't update it to match the study
            if (!UpdateNameBasedOnTheStudy(file))
                UpdateNameBasedOnRules(file);

            string newPatientName = file.DataSet[DicomTags.PatientsName].ToString();
            UpdateItem change = null;

            if (!newPatientName.Equals(orginalPatientsNameInFile, StringComparison.InvariantCultureIgnoreCase))
            {
                change = new UpdateItem(DicomTags.PatientsName, orginalPatientsNameInFile, newPatientName);

                StringBuilder log = new StringBuilder();
                log.AppendLine(String.Format("AUTO-CORRECTION: SOP {0}", file.MediaStorageSopInstanceUid));
                log.AppendLine(String.Format("\tPatient's Name: {0} ==> {1}. ",
                                             change.OriginalValue, change.NewValue));
                Platform.Log(LogLevel.Info, log.ToString());
            }

            return change;
        }
コード例 #9
0
		protected override void ProcessFile(Model.WorkQueueUid queueUid, DicomFile file, ClearCanvas.Dicom.Utilities.Xml.StudyXml stream, bool compare)
		{
            Platform.CheckFalse(compare, "compare");

			SopInstanceProcessor processor = new SopInstanceProcessor(Context);

			FileInfo fileInfo = new FileInfo(file.Filename);
			long fileSize = fileInfo.Length;
			processor.InstanceStats.FileSize = (ulong)fileSize;
			string sopInstanceUid = file.DataSet[DicomTags.SopInstanceUid].GetString(0, "File:" + fileInfo.Name);
			processor.InstanceStats.Description = sopInstanceUid;

			if (Study != null)
			{
				StudyComparer comparer = new StudyComparer();
				DifferenceCollection list = comparer.Compare(file, Study, ServerPartition.GetComparisonOptions());
				if (list != null && list.Count > 0)
				{
					Platform.Log(LogLevel.Warn, "Dicom file contains information inconsistent with the study in the system");
				}
			}

		    string groupID = ServerHelper.GetUidGroup(file, StorageLocation.ServerPartition, WorkQueueItem.InsertTime);
			processor.ProcessFile(groupID, file, stream, false, false, null, null);

			Statistics.StudyInstanceUid = StorageLocation.StudyInstanceUid;
			if (String.IsNullOrEmpty(processor.Modality) == false)
				Statistics.Modality = processor.Modality;

			// Update the statistics
			Statistics.NumInstances++;
		}
コード例 #10
0
        protected override InstancePreProcessingResult PreProcessFile(Model.WorkQueueUid uid, DicomFile file)
        {
            // Return a result indicating the file has been reconciled.
            InstancePreProcessingResult result = new InstancePreProcessingResult {AutoReconciled = true};

        	return result;
        }
コード例 #11
0
ファイル: AutoReconciler.cs プロジェクト: UIKit0/ClearCanvas
        /// <summary>
        /// Processes the specified <see cref="DicomFile"/> object.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        /// <exception cref="TargetStudyInvalidStateException">Thrown when the target study is in invalid state and cannot be updated.</exception>
        public InstancePreProcessingResult Process(DicomFile file)
        {
            Platform.CheckForNullReference(file, "file");

            AutoReconcilerResult preProcessingResult = null;
            
            // Update the file based on the reconciliation in the past
            IList<StudyHistory> histories = FindReconcileHistories(StorageLocation, file);
            if (histories != null && histories.Count > 0)
            {
                preProcessingResult = ApplyHistories(file, histories);
            }

            if (preProcessingResult!=null)
            {
                StringBuilder log = new StringBuilder();
                log.AppendLine(String.Format("AUTO-RECONCILE: {0}. SOP {1}", preProcessingResult.Action, file.MediaStorageSopInstanceUid));
                foreach (UpdateItem change in preProcessingResult.Changes)
                {
                    if (change.NewValue != null && !change.NewValue.Equals(change.OriginalValue))
                    {
                        log.AppendLine(String.Format("\tSet {0}: {1} => {2}", change.Tag, change.OriginalValue, change.NewValue));    
                    }
                }
                Platform.Log(LogLevel.Info, log.ToString());
               
            }
            return preProcessingResult;
        }
コード例 #12
0
		/// <summary>
		/// Load the first instance from the first series of the StudyXml file for a study.
		/// </summary>
		/// <param name="location">The storage location of the study.</param>
		/// <returns></returns>
		protected static DicomFile LoadInstance(StudyStorageLocation location)
		{
			string studyXml = Path.Combine(location.GetStudyPath(), location.StudyInstanceUid + ".xml");

			if (!File.Exists(studyXml))
			{
				return null;
			}

			FileStream stream = FileStreamOpener.OpenForRead(studyXml, FileMode.Open);
			var theDoc = new XmlDocument();
			StudyXmlIo.Read(theDoc, stream);
			stream.Close();
			stream.Dispose();
			var xml = new StudyXml();
			xml.SetMemento(theDoc);
            
			IEnumerator<SeriesXml> seriesEnumerator = xml.GetEnumerator();
			if (seriesEnumerator.MoveNext())
			{
				SeriesXml seriesXml = seriesEnumerator.Current;
				IEnumerator<InstanceXml> instanceEnumerator = seriesXml.GetEnumerator();
				if (instanceEnumerator.MoveNext())
				{
					InstanceXml instance = instanceEnumerator.Current;
					var file = new DicomFile("file.dcm",new DicomAttributeCollection(), instance.Collection)
						{TransferSyntax = instance.TransferSyntax};
					return file;
				}
			}

			return null;
		}
コード例 #13
0
		public override bool Apply(DicomFile file)
		{
            if (_uidMapper == null)
                return true; // Nothing to do

			string oldSeriesUid = file.DataSet[DicomTags.SeriesInstanceUid].GetString(0, String.Empty);
			string oldSopUid = file.DataSet[DicomTags.SopInstanceUid].GetString(0, String.Empty);

			string newSeriesUid;
            if (_uidMapper.ContainsSeries(oldSeriesUid))
                newSeriesUid = _uidMapper.FindNewSeriesUid(oldSeriesUid);
            else
            {
                newSeriesUid = DicomUid.GenerateUid().UID;
                _uidMapper.AddSeries(_originalStudy.StudyInstanceUid, _targetStudy.StudyInstanceUid, oldSeriesUid, newSeriesUid);
            }

			string newSopInstanceUid;
			if (_uidMapper.ContainsSop(oldSopUid))
				newSopInstanceUid = _uidMapper.FindNewSopUid(oldSopUid);
			else
			{
				newSopInstanceUid = DicomUid.GenerateUid().UID;
				_uidMapper.AddSop(oldSopUid, newSopInstanceUid);
			}

			file.DataSet[DicomTags.SeriesInstanceUid].SetStringValue(newSeriesUid);
			file.DataSet[DicomTags.SopInstanceUid].SetStringValue(newSopInstanceUid);
			file.MediaStorageSopInstanceUid = newSopInstanceUid;

            // add Source Image Sequence
            AddSourceImageSequence(file, oldSopUid);

		    return true;
		}
コード例 #14
0
ファイル: InsertInstanceCommand.cs プロジェクト: nhannd/Xian
		public InsertInstanceCommand(DicomFile file, StudyStorageLocation location)
			: base("Insert Instance into Database")
		{
			Platform.CheckForNullReference(file, "Dicom File object");
			Platform.CheckForNullReference(location, "Study Storage Location");

			_file = file;
			_storageLocation = location;
		}
コード例 #15
0
		public UpdateInstanceCommand(ServerPartition partition,
								  StudyStorageLocation studyLocation,
								  DicomFile file)
			: base("Update existing SOP Instance")
		{
			_partition = partition;
			_studyLocation = studyLocation;
			_file = file;
		}
コード例 #16
0
        //public static void ConvertBmpToDicomAndAddToExistingFolder(string bmpFilePath, string dicomFolderPath, string newFileName = "")
        //{
        //    if (string.IsNullOrEmpty(newFileName)) newFileName = Path.GetFileNameWithoutExtension(bmpFilePath);
        //    if (Directory.GetFiles(dicomFolderPath)
        //        .Any(f => Path.GetFileName(f).ToLower().Contains(newFileName ?? throw new ArgumentNullException(nameof(newFileName)))))
        //        newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");

        //    var dicomFileHighestInstanceNo = GetDicomFileWithHighestInstanceNumber(dicomFolderPath);
        //    var headers = GetDicomTags(dicomFileHighestInstanceNo);
        //    var newFilePath = Path.Combine(dicomFolderPath, newFileName ?? throw new ArgumentNullException(nameof(newFileName)));

        //    ConvertBmpToDicom(bmpFilePath, newFilePath, dicomFileHighestInstanceNo);
        //    var newFileInstanceNumber = headers.InstanceNumber.Values == null || headers.InstanceNumber.Values.Length < 1 ? 1 : int.Parse(headers.InstanceNumber.Values[0]) + 1;
        //    headers.InstanceNumber.Values = new[] { newFileInstanceNumber.ToString() };
        //    UpdateDicomHeaders(newFilePath, headers, DicomNewObjectType.NewImage);
        //}

        public static string GetPatientIdFromDicomFile(string dicomFilePath)
        {
            var dcmFile = new ClearCanvas.Dicom.DicomFile(dicomFilePath);

            dcmFile.Load(dicomFilePath);
            var patientIdTag = dcmFile.DataSet[1048608].Values as string[];

            return(patientIdTag?[0]);
        }
コード例 #17
0
        /// <summary>
        /// Updates the given Dicom headers without trying to be clever.
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="tags"></param>
        public static void ForceUpdateDicomHeaders(string filepath, DicomTagCollection tags)
        {
            var dcmFile = new ClearCanvas.Dicom.DicomFile(filepath);

            dcmFile.Load(filepath);

            tags.ToList().ForEach(tag => UpdateTag(dcmFile, tag));
            dcmFile.Save();
        }
コード例 #18
0
ファイル: StorageScp.cs プロジェクト: UIKit0/ClearCanvas
        /// <summary>
        /// Converts a <see cref="DicomMessage"/> instance into a <see cref="DicomFile"/>.
        /// </summary>
        /// <remarks>This routine sets the Source AE title, </remarks>
        /// <param name="message"></param>
        /// <param name="filename"></param>
        /// <param name="assocParms"></param>
        /// <returns></returns>
        protected static DicomFile ConvertToDicomFile(DicomMessage message, string filename, AssociationParameters assocParms)
        {
            // This routine sets some of the group 0x0002 elements.
            DicomFile file = new DicomFile(message, filename);

            file.SourceApplicationEntityTitle = assocParms.CallingAE;
            file.TransferSyntax = message.TransferSyntax;
            return file;
        }
コード例 #19
0
ファイル: MockImageSop.cs プロジェクト: m-berkani/ClearCanvas
		private static ISopDataSource CreateSopDataSource()
		{
			var uid = DicomUid.GenerateUid().UID;
			var dcf = new DicomFile();
			dcf.MediaStorageSopInstanceUid = uid;
			dcf.MediaStorageSopClassUid = DicomUids.SecondaryCaptureImageStorage.UID;
			dcf.DataSet[DicomTags.SopInstanceUid].SetStringValue(uid);
			dcf.DataSet[DicomTags.SopClassUid].SetStringValue(DicomUids.SecondaryCaptureImageStorage.UID);
			return new TestDataSource(dcf);
		}
コード例 #20
0
		/// <summary>
		/// Constructor.
		/// </summary>
		/// <param name="path">The path to save the file.</param>
		/// <param name="file">The file to save.</param>
		/// <param name="failOnExists">If the file already exists, the file will save.</param>
		public SaveDicomFileCommand(string path, DicomFile file, bool failOnExists)
			: base("Save DICOM Message", true)
		{
			Platform.CheckForNullReference(path, "File name");
			Platform.CheckForNullReference(file, "Dicom File object");

			_path = path;
			_file = file;
			_failOnExists = failOnExists;
		}
コード例 #21
0
		public static CommandBase CreateSaveDicomFileCommand(string path, DicomFile dcf, bool failIfExists)
		{
			switch (_disposition)
			{
				case FileProcessingDisposition.Availability:
					return new SaveDicomFileCommand(path, dcf, failIfExists);
				case FileProcessingDisposition.Performance:
				default:
					return new FastSaveDicomFileCommand(path, dcf, failIfExists);
			}
		}
コード例 #22
0
		public InsertStudyXmlCommand(DicomFile file, StudyXml stream, StudyStorageLocation storageLocation)
			: base("Insert into Study XML", true)
		{
			Platform.CheckForNullReference(file, "Dicom File object");
			Platform.CheckForNullReference(stream, "StudyStream object");
			Platform.CheckForNullReference(storageLocation, "Study Storage Location");

			_file = file;
			_stream = stream;
			_studyStorageLocation = storageLocation;
		}
コード例 #23
0
		public StreamingSopDataSource(DicomFile file, IDicomFileLoader loader)
			: base(file)
		{
			if (!loader.CanLoadCompleteHeader)
				throw new ArgumentException("Loader must be capable of retrieving the full image header.", "loader");
			if (!loader.CanLoadFramePixelData)
				throw new ArgumentException("Loader must be capable of loading frame pixel data.", "loader");

			_loader = loader;
			//Have to assume this to be the case.
			_fullHeaderRetrieved = true;
		}
コード例 #24
0
 /// <summary>
 /// Update the tags for the given files. Files will be given a generated SeriesInstanceUid and ImageUid.
 /// </summary>
 /// <param name="filesPath">List of files to apply the tags to.</param>
 /// <param name="tags">The tags which you'd like to apply to the above files.</param>
 public static void GenerateSeriesHeaderForAllFiles(string[] filesPath, DicomTagCollection tags, int uidpostfix = 1)
 {
     tags.SeriesInstanceUid.Values = new[] { GenerateNewSeriesUid(uidpostfix.ToString()) };
     tags.ImageUid.Values          = new[] { GenerateNewImageUid() };
     foreach (var filepath in filesPath)
     {
         var dcmFile = new ClearCanvas.Dicom.DicomFile(filepath);
         dcmFile.Load(filepath);
         dcmFile = UpdateTags(dcmFile, tags, TagType.Series);
         dcmFile.Save(filepath);
     }
 }
コード例 #25
0
        public static void UpdateImagePositionFromReferenceSeries(string[] dicomFilesToUpdate, string[] orientationDicomFiles)
        {
            if (dicomFilesToUpdate == null || dicomFilesToUpdate.Length == 0)
            {
                throw new ArgumentNullException("Orientation Dicom files not available to read from");
            }
            if (orientationDicomFiles == null || orientationDicomFiles.Length == 0)
            {
                throw new ArgumentNullException("Dicom files to copy orientation data to not available");
            }

            if (dicomFilesToUpdate.Length != orientationDicomFiles.Length)
            {
                throw new Exception("Number of files in \"Orientation dicom\" folder and \"Dicom Files to Update\" do not match");
            }

            var orderedFilesToUpdate = dicomFilesToUpdate
                                       .OrderBy((f) =>
            {
                var vals = GetDicomTags(f).InstanceNumber.Values;
                return(vals != null && vals.Length > 0 ?
                       int.Parse(GetDicomTags(f).InstanceNumber.Values[0])
                        : 0);
            }).ToArray();

            var orderedOrientationFiles = orientationDicomFiles
                                          .OrderBy((f) =>
            {
                var vals = GetDicomTags(f).InstanceNumber.Values;
                return(vals != null && vals.Length > 0 ?
                       int.Parse(GetDicomTags(f).InstanceNumber.Values[0])
                        : 0);
            }).ToArray();

            for (var i = 0; i < orderedFilesToUpdate.Count(); i++)
            {
                var fileToUpdate    = orderedFilesToUpdate[i];
                var orientationFile = orderedOrientationFiles[i];

                var imagePatientOrientation = GetDicomTags(orientationFile).ImagePositionPatient;
                var imageOrientation        = GetDicomTags(orientationFile).ImageOrientation;
                var frameOfReferenceUid     = GetDicomTags(orientationFile).FrameOfReferenceUid;
                var sliceLocation           = GetDicomTags(orientationFile).SliceLocation;

                var dcmFile = new ClearCanvas.Dicom.DicomFile();
                dcmFile.Load(fileToUpdate);
                dcmFile = UpdateArrayTag(dcmFile, imagePatientOrientation, imagePatientOrientation.Values);
                dcmFile = UpdateArrayTag(dcmFile, imageOrientation, imageOrientation.Values);
                dcmFile = UpdateArrayTag(dcmFile, frameOfReferenceUid, frameOfReferenceUid.Values);
                dcmFile = UpdateArrayTag(dcmFile, sliceLocation, sliceLocation.Values);
                dcmFile.Save(fileToUpdate);
            }
        }
コード例 #26
0
ファイル: ImageStreamingContext.cs プロジェクト: nhannd/Xian
        public ImageStreamingContext(HttpListenerContext context)
        {
            Request = context.Request;
            Response = context.Response;
            NameValueCollection query = Request.QueryString;

            #region INIT STUFF FOR PERFORMANCE TESTING
            #if DEBUG 

            if (query["testcompressed"] != null)
            {
                testCompressed= true;
            }
            else if (query["testuncompressed"] != null)
            {
                testUncompressed = true;
            }
            if (_testCompressedImage == null)
            {
                using (Stream stream = typeof(ImageStreamingContext).Assembly.GetManifestResourceStream("ClearCanvas.ImageServer.Services.Streaming.ImageStreaming.Test.TestSamples.compressed.dcm"))
                {
                    DicomFile file = new DicomFile();
                    file.Load(stream);

                    _testCompressedImage = DicomPixelData.CreateFrom(file);
                }
                
            }

            if (_testUncompressedImage == null)
            {
                using (Stream stream = typeof(ImageStreamingContext).Assembly.GetManifestResourceStream("ClearCanvas.ImageServer.Services.Streaming.ImageStreaming.Test.TestSamples.uncompressed.dcm"))
                {
                    DicomFile file = new DicomFile();
                    file.Load(stream);

                    _testUncompressedImage = DicomPixelData.CreateFrom(file);
                }
                
            }
            #endif

            #endregion

            _frameNumber = 0;
            if (query["FrameNumber"] != null)
                int.TryParse(query["FrameNumber"], out _frameNumber);

            _nextSeriesUid = query["nextSeriesUid"];
            _nextSopUid = query["nextObjectUid"];

        }
コード例 #27
0
ファイル: ImageSetGroupsTests.cs プロジェクト: nhannd/Xian
		private ImageSop CreateImageSop(string patientId, string studyUid, string seriesUid, string sopUid)
		{
			DicomAttributeCollection dataSet = new DicomAttributeCollection();
			base.SetupMR(dataSet);
			DicomFile file = new DicomFile(null, new DicomAttributeCollection(), dataSet);
			TestDataSource dataSource = new TestDataSource(file);
			file.DataSet[DicomTags.PatientId].SetStringValue(patientId);
			file.DataSet[DicomTags.StudyInstanceUid].SetStringValue(studyUid);
			file.DataSet[DicomTags.SeriesInstanceUid].SetStringValue(seriesUid);
			file.DataSet[DicomTags.SopInstanceUid].SetStringValue(sopUid);

			return new ImageSop(dataSource);
		}
コード例 #28
0
ファイル: TileEntityHandlerTest.cs プロジェクト: nhannd/Xian
        public void TestProcessMessage()
        {
            
            try
            {

                Assert.IsNotNull(SynchronizationContext.Current, "SynchronizationContext.Current");
                
                DicomFile file = new DicomFile("TileEntityHandlerTest.dcm");
                DicomAttributeCollection dataSet = file.DataSet;
                SetupSecondaryCapture(dataSet);
                file.Save();

                
                ImageViewerComponent viewer = new ImageViewerComponent();
                viewer.Start();

                viewer.LoadImages(new[] { "TileEntityHandlerTest.dcm" });

                ManualResetEvent signal = new ManualResetEvent(false);
                viewer.EventBroker.LayoutManagerCompleted += (s, e) => signal.Set();

                viewer.Layout();
                Console.WriteLine("Waiting for layout to complete");
                if (!signal.WaitOne(20000))
                    Assert.Fail("Abort: something is not working properly.");

                Console.WriteLine("Layout completed");
                Assert.IsNotNull(viewer.PhysicalWorkspace);
                Assert.IsNotNull(viewer.PhysicalWorkspace.ImageBoxes[0]);
                Assert.IsNotNull(viewer.PhysicalWorkspace.ImageBoxes[0].Tiles[0]);

                Tile tile = viewer.PhysicalWorkspace.ImageBoxes[0].Tiles[0] as Tile;

                Assert.IsNotNull(tile.PresentationImage);

                MockApplicationContext context = new MockApplicationContext();

                TileEntityHandler handler = new TileEntityHandler { ApplicationContext = context };
                handler.SetModelObject(tile);
                ChangeClientRectangle(context, handler, 0, 0, 512, 512, "Case: Size is even");
                ChangeClientRectangle(context, handler, 0, 0, 311, 311, "Case: Size is odd");
                ChangeClientRectangle(context, handler, 10, 10, 300, 301, "Case: Left,Top are positive");
                ChangeClientRectangle(context, handler, -10, -10, 512, 512, "Case: Left,Top are negative");
                
            }
            finally
            {
                File.Delete("TileEntityHandlerTest.dcm");
            }
        }
コード例 #29
0
		public TestPresentationImage() : base(TestPattern.CreateRGBKCorners(new Size(_width, _height)))
		{
			DicomFile dcf = new DicomFile();
			dcf.DataSet[DicomTags.StudyInstanceUid].SetStringValue("1");
			dcf.DataSet[DicomTags.SeriesInstanceUid].SetStringValue("2");
			dcf.DataSet[DicomTags.SopInstanceUid].SetStringValue("3");
			dcf.DataSet[DicomTags.SopClassUid].SetStringValue(SopClass.SecondaryCaptureImageStorageUid);
			dcf.DataSet[DicomTags.InstanceNumber].SetStringValue("1");
			dcf.DataSet[DicomTags.NumberOfFrames].SetStringValue("1");
			dcf.MetaInfo[DicomTags.TransferSyntaxUid].SetStringValue(TransferSyntax.ImplicitVrLittleEndianUid);
			dcf.MetaInfo[DicomTags.MediaStorageSopClassUid].SetStringValue(SopClass.SecondaryCaptureImageStorageUid);
			dcf.MetaInfo[DicomTags.MediaStorageSopInstanceUid].SetStringValue("3");
			_imageSop = new ImageSop(new TestDataSource(dcf));
		}
コード例 #30
0
        /// <summary>
        /// Gets the tags for a dicom file.
        /// </summary>
        /// <param name="filePath">The dicom file.</param>
        /// <returns></returns>
        public static DicomTagCollection GetDicomTags(string filePath)
        {
            var dcmFile = new ClearCanvas.Dicom.DicomFile(filePath);

            dcmFile.Load(filePath);
            var tags        = new DicomTagCollection();
            var updatedTags = new DicomTagCollection();

            foreach (var tag in tags.ToList())
            {
                updatedTags.SetTagValue(tag.GetTagValue(), dcmFile.DataSet[tag.GetTagValue()].Values);
            }
            return(updatedTags);
        }
コード例 #31
0
ファイル: MainDialog.cs プロジェクト: scottshea/monodicom
        private void ButtonLoadFile_Click(object sender, EventArgs e)
        {
            openFileDialog.DefaultExt = "dcm";
            openFileDialog.ShowDialog();

            DicomFile dicomFile = new DicomFile(openFileDialog.FileName);

            DicomReadOptions options = new DicomReadOptions();

            dicomFile.Load(options);
            


            _theStream.AddFile(dicomFile);

        }
コード例 #32
0
 private static DicomFile UpdateTags(
     ClearCanvas.Dicom.DicomFile dcmFile, DicomTagCollection newTags, TagType tagType, bool overwriteIfNotProvided = false)
 {
     if (newTags == null)
     {
         return(dcmFile);
     }
     newTags.ToList().ForEach(tag =>
     {
         if (tag.DicomTagType == tagType)
         {
             dcmFile = UpdateTag(dcmFile, tag, overwriteIfNotProvided);
         }
     });
     return(dcmFile);
 }
コード例 #33
0
ファイル: SeriesSopUpdateCommand.cs プロジェクト: nhannd/Xian
	    private void AddSourceImageSequence(DicomFile file, string oldSopUid)
	    {
	        DicomAttributeSQ sourceImageSq;
	        if (!file.DataSet.Contains(DicomTags.SourceImageSequence))
	        {
	            sourceImageSq = new DicomAttributeSQ(DicomTags.SourceImageSequence);
	            file.DataSet[DicomTags.SourceImageSequence] = sourceImageSq;
	        }
	        else
	            sourceImageSq = file.DataSet[DicomTags.SourceImageSequence] as DicomAttributeSQ;

	        DicomSequenceItem item = new DicomSequenceItem();
	        item[DicomTags.ReferencedSopClassUid].SetStringValue(file.SopClass.Uid);
	        item[DicomTags.ReferencedSopInstanceUid].SetStringValue(oldSopUid);
	        sourceImageSq.AddSequenceItem(item);
	    }
コード例 #34
0
		public MockDicomPresentationImage(string filename) : base(new GrayscaleImageGraphic(10, 10))
		{
			if (Path.IsPathRooted(filename))
				_filename = filename;
			else
				_filename = Path.Combine(Environment.CurrentDirectory, filename);

			_dicomFile = new DicomFile();
			_dicomFile.DataSet[DicomTags.SopClassUid].SetStringValue(SopClass.SecondaryCaptureImageStorageUid);
			_dicomFile.DataSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);
			_dicomFile.MetaInfo[DicomTags.MediaStorageSopClassUid].SetStringValue(_dicomFile.DataSet[DicomTags.SopClassUid].ToString());
			_dicomFile.MetaInfo[DicomTags.MediaStorageSopInstanceUid].SetStringValue(_dicomFile.DataSet[DicomTags.SopInstanceUid].ToString());
			_dicomFile.Save(_filename);
			_sopDataSource = new LocalSopDataSource(_dicomFile);
			_imageSop = new ImageSop(_sopDataSource);
			_frame = new MockFrame(_imageSop, 1);
		}
コード例 #35
0
ファイル: InsertStudyXmlCommand.cs プロジェクト: nhannd/Xian
        public InsertStudyXmlCommand(DicomFile file, StudyXml studyXml, StudyLocation storageLocation, bool writeFile)
            : base("Insert Study Xml", true)
        {
            _file = file;
            _studyXml = studyXml;
            _studyStorageLocation = storageLocation;
            _writeFile = writeFile;

            _settings = new StudyXmlOutputSettings
                            {
                                IncludePrivateValues = StudyXmlTagInclusion.IgnoreTag,
                                IncludeUnknownTags = StudyXmlTagInclusion.IgnoreTag,
                                IncludeLargeTags = StudyXmlTagInclusion.IncludeTagExclusion,
                                MaxTagLength = 2048,
                                IncludeSourceFileName = true
                            };
        }
コード例 #36
0
	    public InsertOrUpdateEntryCommand(String groupId,
		                                        StudyStorageLocation studyLocation, 
                                                DicomFile file, String duplicateStoragePath, String relativePath,
                                                 List<DicomAttributeComparisonResult> reasons) 
			: base("Insert Duplicate Queue Entry Command")
		{
            Platform.CheckForNullReference(groupId, "groupId");
			Platform.CheckForNullReference(studyLocation, "studyLocation");
			Platform.CheckForNullReference(file, "file");

			_file = file;
			_studyLocation = studyLocation;
            _groupId = groupId;
	        _duplicateStoragePath = duplicateStoragePath;
		    _relativePath = relativePath;
	        _reasons = reasons;
		}
コード例 #37
0
        public ImportSopResponse ImportSop(ImportSopRequest request)
        {
            try
            {
                var theFile = new DicomFile(string.Format("{0}{1}", request.SopInstanceUid, ServerPlatform.DicomFileExtension));

                using (var stream = new LargeMemoryStream(request.SopInstance))
                {
                    theFile.Load(stream);
                }

                var partition = ServerPartitionMonitor.Instance.GetPartition(request.CalledAETitle);

                string aeTitle = theFile.SourceApplicationEntityTitle;

                if (_importerContext == null)
                    _importerContext = new SopInstanceImporterContext(
                        String.Format("{0}_{1}", aeTitle, DateTime.Now.ToString("yyyyMMddhhmmss")),
                        partition.AeTitle, partition);

                var utility = new SopInstanceImporter(_importerContext);


                var importResult = utility.Import(theFile);
                if (!importResult.Successful)
                    Platform.Log(LogLevel.Error, "Failure importing file file from Web Service: {0}, SOP Instance UID: {1}", importResult.ErrorMessage, request.SopInstanceUid);
                else
                    Platform.Log(LogLevel.Info, "Processed import for SOP through Web Service: {0}.", request.SopInstanceUid);

                var result = new ImportSopResponse
                    {
                        DicomStatusCode = importResult.DicomStatus.Code,
                        FailureMessage = importResult.ErrorMessage,
                        Successful = importResult.Successful
                    };

                return result;
            }
            catch (Exception ex)
            {
                var message = string.Format("Failed to import files: {0}, SOP Instance UID: {1}", ex.Message, request.SopInstanceUid);
                Platform.Log(LogLevel.Error, message);
                throw new FaultException(message);
            }
        }
コード例 #38
0
        /// <summary>
        /// This method will update a tag
        /// </summary>
        /// <param name="dcmFile"></param>
        /// <param name="newTag"></param>
        /// <param name="overwriteIfNotProvided"></param>
        /// <returns></returns>
        private static DicomFile UpdateTag(
            ClearCanvas.Dicom.DicomFile dcmFile, IDicomTag newTag, bool overwriteIfNotProvided = false)
        {
            if (newTag?.Values == null && !overwriteIfNotProvided)
            {
                return(dcmFile);
            }
            var value = newTag?.Values != null && newTag.Values.Length > 0 ? newTag.Values[0] : "";

            if (newTag?.GetValueType() == typeof(string[]))
            {
                var vals = new string[newTag.Values.Length];
                newTag.Values.CopyTo(vals, 0);
                dcmFile.DataSet[newTag.GetTagValue()].Values = vals;
            }
            else if (newTag?.GetValueType() == typeof(string))
            {
                dcmFile.DataSet[newTag.GetTagValue()].Values = value;
            }
            return(dcmFile);
        }
コード例 #39
0
    public void HandleAllGetRequests(HttpListenerContext context)
    {
        var    rc        = new ResponseClass();
        string studyuid  = context.Request.QueryString["studyuid"];
        string seriesuid = context.Request.QueryString["seriesuid"];
        string check     = context.Request.QueryString["check"];

        if (!string.IsNullOrEmpty(check))
        {
            rc.Success = true;
            rc.Message = "";
            rc.Data    = true;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(rc);
            this.SendTextResponse(context, json);
            return;
        }
        var node = ADCM.GetSelectedNode();

        try
        {
            LOG.Write("New request");
            if (string.IsNullOrEmpty(studyuid) || string.IsNullOrEmpty(seriesuid))
            {
                throw new Exception("No studyuid or seriesuid provided");
            }
            bool downloaded = ADCM.DownloadOneSeries(studyuid, seriesuid);
            if (!downloaded)
            {
                throw new Exception("Unable to download study");
            }
            string seriesPath = Path.Combine(node.LocalStorage, studyuid, seriesuid);
            if (!Directory.Exists(seriesPath))
            {
                throw new Exception("Series path not found: " + seriesPath);
            }
            var     dcmFiles  = Directory.GetFiles(seriesPath, "*.dcm");
            string  filetouse = null;
            decimal mid       = dcmFiles.Length / 2;
            int     index     = (int)Math.Ceiling(mid);
            for (int i = index; i < dcmFiles.Length; i++)
            {
                var dcm = dcmFiles[i];
                ClearCanvas.Dicom.DicomFile dcmFile = new ClearCanvas.Dicom.DicomFile(dcm);
                dcmFile.Load();
                ClearCanvas.ImageViewer.StudyManagement.LocalSopDataSource localds = new ClearCanvas.ImageViewer.StudyManagement.LocalSopDataSource(dcmFile);
                if (!localds.IsImage)
                {
                    continue;
                }
                else
                {
                    filetouse = dcm;
                    break;
                }
            }
            if (string.IsNullOrEmpty(filetouse))
            {
                for (int i = 0; i < dcmFiles.Length; i++)
                {
                    var dcm = dcmFiles[i];
                    ClearCanvas.Dicom.DicomFile dcmFile = new ClearCanvas.Dicom.DicomFile(dcm);
                    dcmFile.Load();
                    ClearCanvas.ImageViewer.StudyManagement.LocalSopDataSource localds = new ClearCanvas.ImageViewer.StudyManagement.LocalSopDataSource(dcmFile);
                    if (!localds.IsImage)
                    {
                        continue;
                    }
                    else
                    {
                        filetouse = dcm;
                        break;
                    }
                }
            }
            if (string.IsNullOrEmpty(filetouse))
            {
                throw new Exception("Unable to find image in downloaded DICOM files");
            }
            if (!File.Exists(filetouse))
            {
                throw new Exception("Unable to find DICOM file to use");
            }

            string base64String = Convert.ToBase64String(AIMG.GetImageBytesFromDcm(filetouse));
            base64String = "data:image/jpeg;base64," + base64String;
            rc.Success   = true;
            rc.Message   = "";
            rc.Data      = base64String;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(rc);
            this.SendTextResponse(context, json);
        }
        catch (Exception ex)
        {
            LOG.Write("ERROR: " + ex.Message);
            rc.Data    = null;
            rc.Success = false;
            rc.Message = ex.Message;
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(rc);
            this.SendTextResponse(context, json);
        }
        finally
        {
            string studypath = Path.Combine(node.LocalStorage, studyuid);
            if (Directory.Exists(studypath))
            {
                Directory.Delete(studypath, true);
            }
        }
    }
コード例 #40
0
        /// <summary>
        /// Process the rule
        /// </summary>
        /// <param name="file"></param>
        public void Process(ClearCanvas.Dicom.DicomFile file)
        {
            var proposedTs = ClearCanvas.Dicom.TransferSyntax.GetTransferSyntax(OutputTransferSyntax);
            var currentTs  = file.TransferSyntax;

            var bitsStored                = file.DataSet[DicomTags.BitsStored].GetInt16(0, 0);
            var bitsAllocated             = file.DataSet[DicomTags.BitsAllocated].GetInt16(0, 0);
            var samplesPerPixel           = file.DataSet[DicomTags.SamplesPerPixel].GetInt16(0, 0);
            var photometricInterpretation = file.DataSet[DicomTags.PhotometricInterpretation].GetString(0, "");

            log.Info(string.Format(
                         "compress: bits stored {0}, bits allocated {1}, samples per pixel {2}, photometric {3}",
                         bitsStored, bitsAllocated, samplesPerPixel, photometricInterpretation));

            log.Info(string.Format("Compress: Proposed: {0}, current {1}", proposedTs, currentTs));
            log.Info("Checking that proposed transfer syntax is consistent with the dataset");

            ClearCanvas.Dicom.TransferSyntax finalTs = currentTs;

            try
            {
                if (proposedTs == TransferSyntax.JpegBaselineProcess1)
                {
                    ValidateJPEGBaselineProcess1(bitsAllocated, bitsStored, samplesPerPixel, photometricInterpretation);
                }
                else if (proposedTs == TransferSyntax.JpegExtendedProcess24)
                {
                    ValidateJPEGExtendedProcess2And4(bitsAllocated, bitsStored, samplesPerPixel, photometricInterpretation);
                }
                else if (proposedTs == TransferSyntax.JpegLosslessNonHierarchicalFirstOrderPredictionProcess14SelectionValue1)
                {
                    ValidateJpegLosslessNonHierarchicalFirstOrderPredictionProcess14SelectionValue1(bitsAllocated, bitsStored, samplesPerPixel, photometricInterpretation);
                }
                else if (proposedTs == TransferSyntax.Jpeg2000ImageCompression)
                {
                    ValidateJpeg2000Lossy(bitsAllocated, bitsStored, samplesPerPixel, photometricInterpretation);
                }
                else if (proposedTs == TransferSyntax.Jpeg2000ImageCompressionLosslessOnly)
                {
                    ValidateJpeg2000Lossless(bitsAllocated, bitsStored, samplesPerPixel, photometricInterpretation);
                }

                // Compression from non-compressed transfer syntaxes
                if (currentTs == TransferSyntax.ImplicitVrLittleEndian ||
                    currentTs == TransferSyntax.ExplicitVrLittleEndian ||
                    currentTs == TransferSyntax.ExplicitVrBigEndian)
                {
                    // This is fine ... we're compressing something that isn't compressed.
                    finalTs = proposedTs;
                }
                else
                {
                    // Potentially a problem.  We could be moving from a compressed syntax to
                    // another compress syntax.  We know the target syntax is legal for this dataset
                    // but the toolkit pukes when moving encapsulated frames.

                    // TO DO: More work needed here.
                    finalTs = proposedTs;
                }

                log.Info(string.Format("Final ts {0}", finalTs));
            }
            catch (NotSupportedException nse)
            {
                log.Error("Compression would be illegal and will NOT be applied. " + nse.ToString());
            }

            if (currentTs != finalTs)
            {
                file.ChangeTransferSyntax(finalTs);
            }
        }
コード例 #41
0
        void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
        {
            if (message.CommandField == DicomCommandField.CEchoRequest)
            {
                server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.Success);
                return;
            }

            String   studyInstanceUid  = null;
            String   seriesInstanceUid = null;
            DicomUid sopInstanceUid    = null;
            String   patientName       = null;
            String   accession         = null;
            String   instanceNumber    = null;

            bool ok = message.DataSet[DicomTags.SopInstanceUid].TryGetUid(0, out sopInstanceUid);

            if (ok)
            {
                ok = message.DataSet[DicomTags.SeriesInstanceUid].TryGetString(0, out seriesInstanceUid);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.StudyInstanceUid].TryGetString(0, out studyInstanceUid);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.PatientsName].TryGetString(0, out patientName);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.AccessionNumber].TryGetString(0, out accession);
            }
            if (ok)
            {
                ok = message.DataSet[DicomTags.InstanceNumber].TryGetString(0, out instanceNumber);
            }

            if (!ok)
            {
                Platform.Log(LogLevel.Error, "Unable to retrieve UIDs from request message, sending failure status.");

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID,
                                          DicomStatuses.ProcessingFailure);
                return;
            }
            TransferSyntax syntax = association.GetPresentationContext(presentationID).AcceptedTransferSyntax;

            if (List)
            {
                Platform.Log(LogLevel.Info, message.Dump());
            }

            if (Bitbucket)
            {
                Platform.Log(LogLevel.Debug, "Received SOP Instance: {0} for patient {1} in syntax {2}", sopInstanceUid,
                             patientName, syntax.Name);

                server.SendCStoreResponse(presentationID, message.MessageId,
                                          sopInstanceUid.UID,
                                          DicomStatuses.Success);
                return;
            }

            if (!Directory.Exists(StorageLocation))
            {
                Directory.CreateDirectory(StorageLocation);
            }

            var path   = new StringBuilder();
            var series = seriesInstanceUid.Length > 8 ? seriesInstanceUid.Substring(seriesInstanceUid.Length - 8) : seriesInstanceUid;

            path.AppendFormat("{0}{1}{2}{3}{4}", StorageLocation, Path.DirectorySeparatorChar,
                              accession, Path.DirectorySeparatorChar, series);

            Directory.CreateDirectory(path.ToString());

            path.AppendFormat("{0}{1}.dcm", Path.DirectorySeparatorChar, instanceNumber);

            var dicomFile = new ClearCanvas.Dicom.DicomFile(message, path.ToString())
            {
                TransferSyntaxUid            = syntax.UidString,
                MediaStorageSopInstanceUid   = sopInstanceUid.UID,
                ImplementationClassUid       = DicomImplementation.ClassUID.UID,
                ImplementationVersionName    = DicomImplementation.Version,
                SourceApplicationEntityTitle = association.CallingAE,
                MediaStorageSopClassUid      = message.SopClass.Uid
            };


            dicomFile.Save(DicomWriteOptions.None);

            Platform.Log(LogLevel.Debug, "Received SOP Instance: {0} for patient {1} in syntax {2}", sopInstanceUid,
                         patientName, syntax.Name);

            server.SendCStoreResponse(presentationID, message.MessageId,
                                      sopInstanceUid.UID,
                                      DicomStatuses.Success);
        }
コード例 #42
0
 private static DicomFile UpdateArrayTag(
     ClearCanvas.Dicom.DicomFile dcmFile, IDicomTag newTag, IEnumerable value)
 {
     dcmFile.DataSet[newTag.GetTagValue()].Values = value;
     return(dcmFile);
 }