Esempio n. 1
0
        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);

        }
Esempio n. 2
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();
        }
Esempio n. 3
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);
            }
        }
Esempio n. 4
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);
     }
 }
Esempio n. 5
0
        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");
            }
        }
		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);
		}
Esempio n. 7
0
        private void buttonDecompress_Click(object sender, EventArgs e)
        {
            if (this.textBoxSourceFile.Text.Length == 0 || this.textBoxDestinationFile.Text.Length == 0)
            {
                MessageBox.Show("Invalid source or destination filename");
                return;
            }

            DicomFile dicomFile = new DicomFile(textBoxSourceFile.Text);

            dicomFile.Load();

            dicomFile.Filename = textBoxDestinationFile.Text;

            dicomFile.ChangeTransferSyntax(TransferSyntax.ExplicitVrLittleEndian);

            dicomFile.Save();
        }
Esempio n. 8
0
		public MimeTypeProcessorOutput Process(ImageStreamingContext context)
		{
			uint stopTag;
			if (!uint.TryParse(context.Request.QueryString["stopTag"] ?? "", NumberStyles.HexNumber, null, out stopTag))
				stopTag = DicomTags.PixelData;

			if (stopTag > DicomTags.PixelData)
				throw new WADOException(HttpStatusCode.BadRequest,
										"Stop tag must be less than PixelData tag.");

			MimeTypeProcessorOutput output = new MimeTypeProcessorOutput();
			output.ContentType = OutputMimeType;
			DicomFile file = new DicomFile(context.ImagePath);
			file.Load(stopTag, DicomReadOptions.Default);

			output.ContentType = OutputMimeType;

			MemoryStream memStream = new MemoryStream();
			file.Save(memStream, DicomWriteOptions.Default);
			output.Output = memStream.ToArray();

			return output;
		}
        public void AssertTagValueChanged(uint tag, string valueToSet, string originalCharacterSet, string expectedNewCharacterSet)
        {
            DicomAttributeCollection dataset = new DicomAttributeCollection();
            SetupDataSet(dataset, originalCharacterSet);
            DicomFile file = new DicomFile("test", CreateMetaInfo(), dataset);

            Assert.AreEqual(originalCharacterSet, file.DataSet[DicomTags.SpecificCharacterSet].ToString());

            SetTagCommand cmd = new SetTagCommand(tag, valueToSet);

            Assert.AreEqual(cmd.CanSaveInUnicode, UnicodeAllowed, "SetTagCommand.CanSaveInUnicode returns an incorrect value");

			var sq = new OriginalAttributesSequence
			{
				ModifiedAttributesSequence = new DicomSequenceItem(),
				ModifyingSystem = ProductInformation.Component,
				ReasonForTheAttributeModification = "CORRECT",
				AttributeModificationDatetime = Platform.Time,
				SourceOfPreviousValues = file.SourceApplicationEntityTitle
			};

            Assert.IsTrue(cmd.Apply(file, sq), "SetTagCommand.Apply failed");

            var filename = string.Format("Test-{0}.dcm", DicomTagDictionary.GetDicomTag(tag).Name);
            Assert.IsTrue(file.Save(filename), "Unable to save dicom file");
            file = new DicomFile(filename);
            file.Load();

            if (valueToSet == null)
                Assert.AreEqual(string.Empty, file.DataSet[tag].ToString());
            else
                Assert.AreEqual(valueToSet, file.DataSet[tag].ToString());

            Assert.IsTrue(file.DataSet[DicomTags.SpecificCharacterSet].ToString().Equals(expectedNewCharacterSet));

            Delete(filename);

        }
Esempio n. 10
0
        //private static void WriteLog(string s)
        //{
        //    File.AppendAllText("C:\\_store.txt", string.Format("{0}\n",s));
        //}

        /// <summary>
        /// Hàm xử lý khi nhận xong dữ liệu Dicom
        /// </summary>
        /// <param name="server"></param>
        /// <param name="association"></param>
        /// <param name="presentationId"></param>
        /// <param name="message"></param>
        void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association,
                                                         byte presentationId, DicomMessage message)
        {
            //wc.Stop();
            //WriteLog(wc.ElapsedMilliseconds.ToString());

            if (message.CommandField == DicomCommandField.CEchoRequest)
            {
                server.SendCEchoResponse(presentationId, message.MessageId, DicomStatuses.Success);
                return;
            }

            String studyInstanceUid = null;
            String seriesInstanceUid = null;
            DicomUid sopInstanceUid;
            //String patientName = null;
            String sex = null;
            sex = message.DataSet[DicomTags.PatientsSex].GetString(0, "O");

            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)
            {
                VBLogger.LogError("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;

            server.SendCStoreResponse(presentationId, message.MessageId,
                                      sopInstanceUid.UID,
                                      DicomStatuses.Success);
            string pathImage = "";
            var path = new StringBuilder();
            path.AppendFormat("{0}{1}{2}{3}{4}", StorageLocation, Path.DirectorySeparatorChar,
                              studyInstanceUid, Path.DirectorySeparatorChar, seriesInstanceUid);

            try
            {
                // Save File
                if (!Directory.Exists(StorageLocation))
                    Directory.CreateDirectory(StorageLocation);
                if (!Directory.Exists(path.ToString()))
                    Directory.CreateDirectory(path.ToString());
                path.AppendFormat("{0}{1}.dcm", Path.DirectorySeparatorChar, sopInstanceUid.UID);

                var dicomFile = new 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);

                //WriteLog(string.Format("Save File OK!: {0}", wc.ElapsedMilliseconds));

                var pd = new DicomUncompressedPixelData(message.DataSet);
                pathImage = path.ToString();
                byte[] thePixels = pd.GetFrame(0);
                var pixData = new UInt16[thePixels.Length/2];
                int h = dicomFile.DataSet[DicomTags.Rows].GetUInt16(0, 0);
                int w = dicomFile.DataSet[DicomTags.Columns].GetUInt16(0, 0);
                UInt16 max = 0, min = UInt16.MaxValue;
                //min = pd.ge
                unsafe
                {
                    fixed (byte* pixPointer = thePixels)
                    {
                        var pP = (UInt16*) pixPointer;
                        for (int i = 0; i < w*h; ++i)
                        {
                            pixData[i] = *pP;
                            if (min > pixData[i]) min = pixData[i];
                            if (max < pixData[i]) max = pixData[i];
                            pP++;
                        }
                    }
                }
                int indexOf = pathImage.LastIndexOf(".dcm");
                pathImage = pathImage.Substring(0, indexOf);
                pathImage = string.Concat(pathImage, "_thumb.jpg");
                string photometricInterpretation;
                message.DataSet[DicomTags.PhotometricInterpretation].TryGetString(0, out photometricInterpretation);
                Bitmap bmp = CreateBitmap(pixData, min, max, w, h, photometricInterpretation);
                bmp.Save(pathImage, ImageFormat.Jpeg);
                bmp.Dispose();
            }
            catch (Exception ex)
            {
                // File.WriteAllText(@"C:\log.txt", ex.ToString());
            }
            //WriteLog(string.Format(" Create Thumbnail OK: {0}", wc.ElapsedMilliseconds));

            String patientName = message.DataSet[DicomTags.PatientsName].GetString(0, "");

            //Xóa các ký tự thừa trong Patient Name
            patientName = patientName.Replace('^', ' ');

            VBLogger.LogInfo("Received SOP Instance: {0} for patient {1}", sopInstanceUid, patientName);


            //Insert Install To DB
            //InsertInstanceToImageServer(association, message.DataSet);

            // FeedBack to Rislink
            string patientId = message.DataSet[DicomTags.PatientId].GetString(0, "");
            string bodyPart = message.DataSet[DicomTags.BodyPartExamined].GetString(0, "");
            string viewPosition = message.DataSet[DicomTags.ViewPosition].GetString(0, "");
            string accessionNumber = message.DataSet[DicomTags.AccessionNumber].GetString(0, "").Trim();
            accessionNumber = accessionNumber == "" ? patientId : accessionNumber;
            //var t = message.DataSet[DicomTags.SourceSerialNumber].GetString(0, "").Trim();
            string requestingAe = association.CallingAE;
            if (viewPosition.Trim() == "")
                viewPosition = message.DataSet[DicomTags.PatientOrientation].GetString(0, "");
            //WriteLog(string.Format("Finish time: {0}",wc.ElapsedMilliseconds));
            var updateOk = SpMergeData(bodyPart, patientId, patientName, path.ToString(), sex, studyInstanceUid, seriesInstanceUid,
                        sopInstanceUid.ToString(), viewPosition, accessionNumber, requestingAe);
            Console.WriteLine(updateOk.ToString(CultureInfo.InvariantCulture));
        }
Esempio n. 11
0
		public AnonymizeStudyOutput AnonymizeStudy(AnonymizeStudyInput input)
		{
			// load study to anonymize
			IDataStoreReader reader = DataAccessLayer.GetIDataStoreReader();
			IStudy study = reader.GetStudy(input.StudyInstanceUID);
			List<ISopInstance> sops = new List<ISopInstance>(study.GetSopInstances());

			// ensure there is a valid output location
			if(string.IsNullOrEmpty(input.OutputDirectory))
			{
				// create temp dir
			}

			string fullPath = Path.GetFullPath(input.OutputDirectory);
			if (!Directory.Exists(fullPath))
			{
				Directory.CreateDirectory(fullPath);
			}

			// set up anonymization data
			StudyData studyData = new StudyData();
			studyData.PatientId = input.PatientId;
			studyData.PatientsNameRaw = input.PatientsName;
			studyData.PatientsBirthDate = input.PatientsBirthDate;
			studyData.PatientsSex = input.PatientsSex;
			studyData.AccessionNumber = input.AccessionNumber;
			studyData.StudyDescription = input.StudyDescription;
			studyData.StudyDate = input.StudyDate;

			DicomAnonymizer anonymizer = new DicomAnonymizer();
			anonymizer.StudyDataPrototype = studyData;

			//The default anonymizer removes the series data, so we just clone the original.
			anonymizer.AnonymizeSeriesDataDelegate =
				delegate(SeriesData original) { return original.Clone(); };

			// anonymize each image in the study
			for (int i = 0; i < sops.Count; ++i)
			{
				ISopInstance sop = sops[i];
				DicomFile file = new DicomFile(sop.GetLocationUri().LocalDiskPath);

				anonymizer.Anonymize(file);

				file.Save(string.Format("{0}\\{1}.dcm", fullPath, i));
			}

			return new AnonymizeStudyOutput(sops.Count);
		}
Esempio n. 12
0
        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();

        }
Esempio n. 13
0
       public static bool Convert2Dicom(byte[] pixelData, string rawFileName, DataRow patientInfo, bool delbeforeSave, string AutoWLPath)
        {
            try
            {
                const string colPid = "PID";
                const string colKVP = "KVP";
                const string colMAS = "MAS";
                const string colDepartmentName = "Department_Name";
                const string colPatientName = "Patient_Name";
                const string colPatientSex = "Patient_Sex";
                const string colPatientAge = "Patient_Age";
                const string colPatientBirthdate = "Patient_Birthdate";
                const string colRegDate = "Reg_Date";
                const string colRegNum = "Reg_Num";
                const string colImgWidth = "IMGWidth";
                const string colImgHeight = "IMGHeigh";
                const string colModalityCode = "Modality_Code";
                const string colAtonomyCode = "Atonomy_Code";
                const string colProjectionCode = "Projection_Code";
                const string colHostpitalName = "Hostpital_Name";
                const string colMonoChrome = "MonoChrome";

                const string _colStudyInstanceUID = "StudyInstanceUID";
                const string colSeriesInstanceUID = "SeriesInstanceUID";
                const string colSOPInstanceUID = "SOPInstanceUID";
                const string colAcqDate = "AcqDate";
                const string colAppName = "AppName";

                const string colBitsStored = "BitsStored";
                const string colHightBit = "HightBit";
                const string colBitsAllocated = "BitsAllocated";

                _bitsStored = TryGetBitsStored(patientInfo, colBitsStored);
                var _HightBit = TryGetBitsStored(patientInfo, colHightBit);
                var _BitsAllocated = TryGetBitsStored(patientInfo, colBitsAllocated);

                var MonoChrome = TryGetString(patientInfo, colMonoChrome, "MONOCHROME2");
                
                var pid = TryGetString(patientInfo, colPid);
                var _KVP = TryGetString(patientInfo, colKVP);
                var _MAS = TryGetString(patientInfo, colMAS);
                var patientName = TryGetString(patientInfo, colPatientName);
                var patientSex = TryGetString(patientInfo, colPatientSex);
                var patientAge = TryGetString(patientInfo, colPatientAge);
                var patientBirthdate = TryGetString(patientInfo, colPatientBirthdate);
                var regDate = TryGetString(patientInfo, colRegDate);
                var regNum = TryGetString(patientInfo, colRegNum);
                var imgWidth = TryGetString(patientInfo, colImgWidth);
                var imgHeigh = TryGetString(patientInfo, colImgHeight);
                var modalityCode = TryGetString(patientInfo, colModalityCode);
                var atonomyCode = TryGetString(patientInfo, colAtonomyCode);
                var projectionCode = TryGetString(patientInfo, colProjectionCode);
                var hostpitalName = TryGetString(patientInfo, colHostpitalName, "BACH MAI HOSTPITAL");
                var departmentName = TryGetString(patientInfo, colDepartmentName, "Khoa chan doan hinh anh");
                string defaultStudyInstanceUID = ClearCanvas.Dicom.DicomUid.GenerateUid().UID;
                string defaultSeriesInstanceUID = defaultStudyInstanceUID + ".1";
                string defaultSOPInstanceUID = defaultSeriesInstanceUID + ".1";
                var StudyInstanceUID = TryGetString(patientInfo, _colStudyInstanceUID, defaultStudyInstanceUID);
                var SeriesInstanceUID = TryGetString(patientInfo, colSeriesInstanceUID, defaultSeriesInstanceUID);
                var SOPInstanceUID = TryGetString(patientInfo, colSOPInstanceUID, defaultSOPInstanceUID);
                var AppName = TryGetString(patientInfo, colAppName, "VBIT");
                string dicomPath = Path.GetDirectoryName(rawFileName);

                // Lấy về tên file Dicom từ file raw
                string dicomFileName = string.Format("{0}{1}{2}.DCM", dicomPath, Path.DirectorySeparatorChar,
                                                     Path.GetFileNameWithoutExtension(rawFileName));

                if (delbeforeSave && File.Exists(dicomFileName)) Try2DelFile(dicomFileName);
                else
                    try2RenameExistedFile(dicomFileName);
                


                //FileStream fs = File.OpenRead(rawFileName);

                //long length = fs.Length;
                long dataLength = pixelData.Length;

                string col = imgWidth.ToString();
                string row = imgHeigh.ToString();
                // GetSize(dataLength, out col, out row);

                // Tạo File Dicom để lưu thông tin
                var dcmFile = new DicomFile(dicomFileName);
                DicomAttributeCollection dicomDataSet = dcmFile.DataSet;

                //Set Tag For File
                DateTime studyTime = DateTime.Now;
                dicomDataSet[DicomTags.SpecificCharacterSet].SetStringValue("ISO_IR 100");
                dicomDataSet[DicomTags.ImageType].SetStringValue("ORIGINAL\\PRIMARY\\OTHER\\M\\FFE");
                dicomDataSet[DicomTags.InstanceCreationDate].SetStringValue(DateParser.ToDicomString(studyTime));
                dicomDataSet[DicomTags.InstanceCreationTime].SetStringValue(TimeParser.ToDicomString(studyTime));
                dicomDataSet[DicomTags.SopClassUid].SetStringValue(SopClass.MrImageStorageUid);
                dicomDataSet[DicomTags.SopInstanceUid].SetStringValue(SOPInstanceUID);
                dicomDataSet[DicomTags.StudyDate].SetStringValue(regDate);
                dicomDataSet[DicomTags.ApplicationName].SetStringValue(AppName);
                dicomDataSet[DicomTags.StudyTime].SetStringValue(TimeParser.ToDicomString(studyTime));
                dicomDataSet[DicomTags.SeriesDate].SetStringValue(regDate);
                dicomDataSet[DicomTags.SeriesTime].SetStringValue(TimeParser.ToDicomString(studyTime));
                dicomDataSet[DicomTags.AccessionNumber].SetStringValue(regNum);
                dicomDataSet[DicomTags.Modality].SetStringValue(modalityCode);
                dicomDataSet[DicomTags.Manufacturer].SetStringValue("VBIT");
                dicomDataSet[DicomTags.StationName].SetStringValue(AppName);
                dicomDataSet[DicomTags.ExposureInMas].SetStringValue(_MAS);
                dicomDataSet[DicomTags.Kvp].SetStringValue(_KVP);
                dicomDataSet[DicomTags.ManufacturersModelName].SetNullValue();
                dicomDataSet[DicomTags.InstitutionName].SetStringValue(hostpitalName);
                dicomDataSet[DicomTags.InstitutionalDepartmentName].SetStringValue(departmentName);
                //dicomDataSet[DicomTags.StudyDescription].SetStringValue("HEART");
                //dicomDataSet[DicomTags.SeriesDescription].SetStringValue("Heart 2D EPI BH TRA");
                //dicomDataSet[DicomTags.PatientsName].SetStringValue("Patient^Test");
                dicomDataSet[DicomTags.PatientsName].SetStringValue(patientName);
                dicomDataSet[DicomTags.PatientId].SetStringValue(pid);
                dicomDataSet[DicomTags.PatientsBirthDate].SetStringValue(patientBirthdate);
                dicomDataSet[DicomTags.PatientsSex].SetStringValue(patientSex);
                dicomDataSet[DicomTags.PatientsAge].SetStringValue(patientAge);
                dicomDataSet[DicomTags.PatientsWeight].SetStringValue("70");
                dicomDataSet[DicomTags.SequenceVariant].SetStringValue("OTHER");
                dicomDataSet[DicomTags.ScanOptions].SetStringValue("CG");
                dicomDataSet[DicomTags.MrAcquisitionType].SetStringValue("2D");
                dicomDataSet[DicomTags.SliceThickness].SetStringValue("2");
                dicomDataSet[DicomTags.RepetitionTime].SetStringValue("857.142883");
                dicomDataSet[DicomTags.EchoTime].SetStringValue("8.712100");
                dicomDataSet[DicomTags.NumberOfAverages].SetStringValue("1");
                dicomDataSet[DicomTags.ImagingFrequency].SetStringValue("63.901150");
                dicomDataSet[DicomTags.ImagedNucleus].SetStringValue("1H");
                dicomDataSet[DicomTags.EchoNumbers].SetStringValue("1");
                dicomDataSet[DicomTags.MagneticFieldStrength].SetStringValue("1.500000");
                dicomDataSet[DicomTags.SpacingBetweenSlices].SetStringValue("10.00000");
                dicomDataSet[DicomTags.NumberOfPhaseEncodingSteps].SetStringValue("81");
                dicomDataSet[DicomTags.EchoTrainLength].SetStringValue("0");
                dicomDataSet[DicomTags.PercentSampling].SetStringValue("63.281250");
                dicomDataSet[DicomTags.PercentPhaseFieldOfView].SetStringValue("68.75000");
                dicomDataSet[DicomTags.DeviceSerialNumber].SetStringValue("1234");
                dicomDataSet[DicomTags.SoftwareVersions].SetStringValue("V1.0");
                dicomDataSet[DicomTags.ProtocolName].SetStringValue("2D EPI BH");
                dicomDataSet[DicomTags.TriggerTime].SetStringValue("14.000000");
                dicomDataSet[DicomTags.LowRRValue].SetStringValue("948");
                dicomDataSet[DicomTags.HighRRValue].SetStringValue("1178");
                dicomDataSet[DicomTags.IntervalsAcquired].SetStringValue("102");
                dicomDataSet[DicomTags.IntervalsRejected].SetStringValue("0");
                dicomDataSet[DicomTags.HeartRate].SetStringValue("56");
                dicomDataSet[DicomTags.ReceiveCoilName].SetStringValue("B");
                dicomDataSet[DicomTags.TransmitCoilName].SetStringValue("B");
                dicomDataSet[DicomTags.InPlanePhaseEncodingDirection].SetStringValue("COL");
                dicomDataSet[DicomTags.FlipAngle].SetStringValue("50.000000");
                dicomDataSet[DicomTags.PatientPosition].SetStringValue("HFS");
                dicomDataSet[DicomTags.StudyInstanceUid].SetStringValue(StudyInstanceUID);
                dicomDataSet[DicomTags.SeriesInstanceUid].SetStringValue(SeriesInstanceUID);
                //dicomDataSet[DicomTags.StudyId].SetStringValue(pid);
                dicomDataSet[DicomTags.SeriesNumber].SetStringValue("1");
                dicomDataSet[DicomTags.AcquisitionNumber].SetStringValue("7");
                dicomDataSet[DicomTags.InstanceNumber].SetStringValue("1");
                dicomDataSet[DicomTags.ImagePositionPatient].SetStringValue("-61.7564\\-212.04848\\-99.6208");
                dicomDataSet[DicomTags.ImageOrientationPatient].SetStringValue("0.861\\0.492\\0.126\\-0.2965");
                dicomDataSet[DicomTags.FrameOfReferenceUid].SetStringValue(DicomUid.GenerateUid().UID);
                dicomDataSet[DicomTags.PositionReferenceIndicator].SetStringValue(null);
                //dicomDataSet[DicomTags.ImageComments].SetStringValue("Test MR Image");
                dicomDataSet[DicomTags.SamplesPerPixel].SetStringValue("1");
                dicomDataSet[DicomTags.PhotometricInterpretation].SetStringValue(MonoChrome);
                dicomDataSet[DicomTags.Rows].SetStringValue(row);
                dicomDataSet[DicomTags.Columns].SetStringValue(col);

                dicomDataSet[DicomTags.PixelSpacing].SetStringValue("0.168\\0.168");
                dicomDataSet[DicomTags.BitsAllocated].SetStringValue(_BitsAllocated.ToString());
                dicomDataSet[DicomTags.BitsStored].SetStringValue(_bitsStored.ToString());
                dicomDataSet[DicomTags.HighBit].SetStringValue(_HightBit.ToString());
                dicomDataSet[DicomTags.PixelRepresentation].SetStringValue("0");

                if (File.Exists(AutoWLPath))
                {
                    switch (_bitsStored)
                    {
                        case 12:
                            dicomDataSet[DicomTags.WindowCenter].SetStringValue("2048");
                            dicomDataSet[DicomTags.WindowWidth].SetStringValue("4095");

                            break;

                        case 14:
                            dicomDataSet[DicomTags.WindowCenter].SetStringValue("8192");
                            dicomDataSet[DicomTags.WindowWidth].SetStringValue("16383");

                            break;

                        case 16:
                            dicomDataSet[DicomTags.WindowCenter].SetStringValue("32767");
                            dicomDataSet[DicomTags.WindowWidth].SetStringValue("65535");
                            break;

                        default:
                            dicomDataSet[DicomTags.WindowCenter].SetStringValue("32767");
                            dicomDataSet[DicomTags.WindowWidth].SetStringValue("65535");
                            break;
                    }

                }

                //dicomDataSet[DicomTags.SmallestImagePixelValue].SetStringValue("32772");
                //dicomDataSet[DicomTags.LargestImagePixelValue].SetStringValue("47745");
                dicomDataSet[DicomTags.RescaleIntercept].SetStringValue("0.");
                dicomDataSet[DicomTags.RescaleSlope].SetStringValue("1.");


                dicomDataSet[DicomTags.ViewPosition].SetStringValue(projectionCode);
                dicomDataSet[DicomTags.BodyPartExamined].SetStringValue(atonomyCode);


                //Gán Dữ liệu ảnh
                var pixels = new DicomAttributeOW(DicomTags.PixelData) { Values = pixelData };
                dicomDataSet[DicomTags.PixelData] = pixels;

                var item = new DicomSequenceItem();
                dicomDataSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);
                item[DicomTags.RequestedProcedureId].SetStringValue("MRR1234");
                item[DicomTags.ScheduledProcedureStepId].SetStringValue("MRS1234");

                item = new DicomSequenceItem();
                dicomDataSet[DicomTags.RequestAttributesSequence].AddSequenceItem(item);

                item[DicomTags.RequestedProcedureId].SetStringValue("MR2R1234");
                item[DicomTags.ScheduledProcedureStepId].SetStringValue("MR2S1234");

                var studyItem = new DicomSequenceItem();

                item[DicomTags.ReferencedStudySequence].AddSequenceItem(studyItem);

                studyItem[DicomTags.ReferencedSopClassUid].SetStringValue(SopClass.MrImageStorageUid);
                studyItem[DicomTags.ReferencedSopInstanceUid].SetStringValue("1.2.3.4.5.6.7.8.9");

                //Set Meta Info
                dicomDataSet[DicomTags.MediaStorageSopClassUid].SetStringValue(
                    dcmFile.DataSet[DicomTags.SopClassUid].GetString(0, ""));
                dicomDataSet[DicomTags.MediaStorageSopInstanceUid].SetStringValue(
                    dcmFile.DataSet[DicomTags.SopInstanceUid].GetString(0, ""));

                dcmFile.TransferSyntax = TransferSyntax.ExplicitVrLittleEndian;

                dicomDataSet[DicomTags.ImplementationClassUid].SetStringValue("1.1.1.1.1.11.1");
                dicomDataSet[DicomTags.ImplementationVersionName].SetStringValue("droc 1.0");

                // Lưu File
                dcmFile.Save();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
		private void Go(IBackgroundTaskContext context)
		{
			string studyUid = DicomUid.GenerateUid().UID;
			string seriesUid = DicomUid.GenerateUid().UID;

			PixelAspectRatioChanger changer = 
				new PixelAspectRatioChanger
              	{
              		IncreasePixelDimensions = _component.IncreasePixelDimensions,
              		NewAspectRatio = new PixelAspectRatio(_component.AspectRatioRow, _component.AspectRatioColumn),
              		RemoveCalibration = _component.RemoveCalibration
              	};

			int i = 0;
			context.ReportProgress(new BackgroundTaskProgress(i, _dicomFileNames.Count, "Exporting ..."));

			try
			{
				foreach (string originalFile in _dicomFileNames)
				{
					var file = new DicomFile(originalFile);
					file.Load(DicomReadOptions.None);

					string sopInstanceUid = DicomUid.GenerateUid().UID;

					file.DataSet[DicomTags.StudyInstanceUid].SetStringValue(studyUid);
					file.DataSet[DicomTags.SeriesInstanceUid].SetStringValue(seriesUid);
					file.DataSet[DicomTags.SopInstanceUid].SetStringValue(sopInstanceUid);

					changer.ChangeAspectRatio(file);

					string outputFileName = Path.Combine(_outputDirectory, String.Format("{0}.dcm", sopInstanceUid));
					file.Save(outputFileName);

					if (context.CancelRequested)
					{
						context.Cancel();
						return;
					}

					context.ReportProgress(new BackgroundTaskProgress(++i, _dicomFileNames.Count + 1, "Exporting ..."));
				}
			}
			catch (Exception e)
			{
				context.Error(e);
				return;
			}

			context.Complete();
		}
Esempio n. 15
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);
        }
        /// <summary>
        /// Apply changes to the file prior to processing it.
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="file"></param>
        protected virtual InstancePreProcessingResult PreProcessFile(WorkQueueUid uid, DicomFile file)
        {
            String contextID = uid.GroupID ?? String.Format("{0}_{1}",
                String.IsNullOrEmpty(file.SourceApplicationEntityTitle) ? ServerPartition.AeTitle : file.SourceApplicationEntityTitle, 
                WorkQueueItem.InsertTime.ToString("yyyyMMddHHmmss"));

            var result = new InstancePreProcessingResult();
            
            var patientNameRules = new PatientNameRules(Study);
            UpdateItem updateItem = patientNameRules.Apply(file);

            result.Modified = updateItem != null;

            var autoBaseReconciler = new AutoReconciler(contextID, StorageLocation);
            InstancePreProcessingResult reconcileResult = autoBaseReconciler.Process(file);
            result.AutoReconciled = reconcileResult != null;
            result.Modified |= reconcileResult != null;
            
            if (reconcileResult!=null && reconcileResult.DiscardImage)
            {
                result.DiscardImage = true;
            }

            // if the studyuid is modified, the file will be deleted by the caller.
            if (file.DataSet[DicomTags.StudyInstanceUid].ToString().Equals(StorageLocation.StudyInstanceUid))
            {
                if (result.Modified)
                    file.Save();
            }

            
            return result;
        }
Esempio n. 17
0
        private void button1_Click(object sender, EventArgs e)
        {
            //CopyTest();

			openFileDialog.Filter = "DICOM|*.dcm";
			openFileDialog.ShowDialog();

            if (!File.Exists(openFileDialog.FileName))
                return;

            DicomFile dicomFile = new DicomFile(openFileDialog.FileName);

            dicomFile.Load();

            //dicomFile.DataSet[DicomTags.PatientsName].SetEmptyValue();
			//dicomFile.DataSet[DicomTags.PatientId].SetEmptyValue();
        	dicomFile.DataSet[DicomTags.SopInstanceUid].SetStringValue(DicomUid.GenerateUid().UID);

			try
			{
				dicomFile.DataSet[DicomTags.PatientsBirthDate].SetStringValue("12/12/2009");
			}
			catch (Exception)
			{
				
			}

			saveFileDialog.Filter = "DICOM|*.dcm";
			if (DialogResult.OK == saveFileDialog.ShowDialog())
			{
				dicomFile.Save(saveFileDialog.FileName);
			}
        }
Esempio n. 18
0
		private void SaveFile(string filename)
		{
			if (_anonymizer != null)
			{
				DicomFile dicomFile = new DicomFile(filename);
				dicomFile.Load(); 

				_anonymizer.Anonymize(dicomFile);

				//anonymize first, then audit, since this is what gets exported.
				_exportedInstances.AddInstance(
				dicomFile.DataSet[DicomTags.PatientId].ToString(),
				dicomFile.DataSet[DicomTags.PatientsName].ToString(),
				dicomFile.DataSet[DicomTags.StudyInstanceUid].ToString(),
				filename);
				
				string fileName = System.IO.Path.Combine(OutputPath, dicomFile.MediaStorageSopInstanceUid);
				fileName += ".dcm";
				CheckFileExists(fileName); // this will never happen for anonymized images.
				if (_canceled)
					return;

				dicomFile.Save(fileName);
			}
			else
			{
				_exportedInstances.AddPath(filename, false);

				string destination = Path.Combine(OutputPath, Path.GetFileName(filename));
				CheckFileExists(destination);
				if (_canceled)
					return;

				File.Copy(filename, destination, true);
			}
		}
Esempio n. 19
0
    /// <summary>
    /// Process C-Echo and C-Store request.
    /// </summary>
    /// <param name="server"></param>
    /// <param name="association"></param>
    /// <param name="presentationID"></param>
    /// <param name="message"></param>
    void IDicomServerHandler.OnReceiveRequestMessage(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
    {

        if (message.CommandField == DicomCommandField.CEchoRequest)
        {
            server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.Success);
            return;
        }
        else if (message.CommandField != DicomCommandField.CStoreRequest)
        {
            server.SendCEchoResponse(presentationID, message.MessageId, DicomStatuses.UnrecognizedOperation);
            return;
        }
        else if (message.CommandField == DicomCommandField.CStoreRequest)
        {
            Platform.Log(LogLevel.Info, message.DataSet.DumpString);

            ClearCanvas.Common.Platform.Log(LogLevel.Info, "C-Store request for {0}.", message.MessageId);
            String studyInstanceUid = null;
            String seriesInstanceUid = null;
            DicomUid sopInstanceUid;
            String patientName = 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)
            //{

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

            try
            {
                // You can save the file by using this
                _storePath = ADCM.GetStoreString();
                if (string.IsNullOrEmpty(_storePath))
                    throw new Exception("No store path provided");
                string studyfolder = Path.Combine(_storePath, studyInstanceUid);
                studyfolder = Path.Combine(studyfolder, seriesInstanceUid);

                if (!Directory.Exists(studyfolder))
                    Directory.CreateDirectory(studyfolder);
                string filename = Path.Combine(studyfolder, message.DataSet[DicomTags.SopInstanceUid].ToString() + ".dcm");
                DicomFile file = new DicomFile(message, filename);
                file.Save(filename, DicomWriteOptions.Default);
                ClearCanvas.Common.Platform.Log(ClearCanvas.Common.LogLevel.Info, "Sending C-Store success response.");
                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid.UID, DicomStatuses.Success);
            }
            catch (Exception ex)
            {
                ClearCanvas.Common.Platform.Log(LogLevel.Error, ex, "Unable to store request {0}.", message.MessageId);

                server.SendCStoreResponse(presentationID, message.MessageId, sopInstanceUid != null ? sopInstanceUid.UID : string.Empty, DicomStatuses.ProcessingFailure);
            }

        }
    }