Example #1
0
        public void UpdateDicomFile(UpdateData updateData)
        {
            DicomFileFormat dicomFile = new DicomFileFormat();

            dicomFile.Load(updateData.DicomFileName, DicomReadOptions.DeferLoadingLargeElements);

            foreach (KeyValuePair <DicomTag, string> kvp in updateData.UpdateDataset)
            {
                dicomFile.Dataset.SetString(kvp.Key, kvp.Value);
            }

            foreach (KeyValuePair <DicomTag, string> kvp in updateData.UpdateMetadata)
            {
                dicomFile.FileMetaInfo.SetString(kvp.Key, kvp.Value);
            }

            dicomFile.Dataset.PreloadDeferredBuffers();
            dicomFile.Save(updateData.DicomFileName, DicomWriteOptions.Default);

            //if (updateData.DicomFileName != null)
            //{
            //    string path = Path.GetDirectoryName(updateData.DicomFilePath);
            //    File.Move(updateData.DicomFilePath, path + @"\" + updateData.DicomFileName);
            //}
        }
Example #2
0
        public CStoreRequestInfo(string fileName, object userModel)
        {
            try {
                _fileName = fileName;
                if (!File.Exists(fileName))
                {
                    throw new FileNotFoundException("Unable to load DICOM file!", fileName);
                }

                DicomTag        stopTag = (userModel != null) ? DicomTags.PixelData : DcmFileMetaInfo.StopTag;
                DicomFileFormat ff      = new DicomFileFormat();
                ff.Load(fileName, stopTag, DicomReadOptions.Default);
                _transferSyntax         = ff.FileMetaInfo.TransferSyntax;
                _originalTransferSyntax = _transferSyntax;
                _sopClass = ff.FileMetaInfo.MediaStorageSOPClassUID;
                _sopInst  = ff.FileMetaInfo.MediaStorageSOPInstanceUID;
                if (userModel != null)
                {
                    ff.Dataset.LoadDicomFields(userModel);
                    _userState = userModel;
                }
                _status = DcmStatus.Pending;
            }
            catch (Exception e) {
                _status    = DcmStatus.ProcessingFailure;
                _exception = e;
                throw;
            }
        }
Example #3
0
        private void OnClickPixelDataMD5(object sender, EventArgs e)
        {
            if (_selected == -1)
            {
                return;
            }

            try {
                DicomFileFormat ff = new DicomFileFormat();
                ff.Load(_files[_selected], DicomReadOptions.Default |
                        DicomReadOptions.KeepGroupLengths |
                        DicomReadOptions.DeferLoadingLargeElements |
                        DicomReadOptions.DeferLoadingPixelData);

                DcmPixelData pixels = new DcmPixelData(ff.Dataset);

                if (pixels.NumberOfFrames == 0)
                {
                    MessageBox.Show(this, "No pixel data", "Pixel Data MD5");
                }
                else if (pixels.NumberOfFrames >= 1)
                {
                    MessageBox.Show(this, pixels.ComputeMD5(), String.Format("Pixel Data MD5 [{0} frames]", pixels.NumberOfFrames));
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            } catch {
            }
        }
Example #4
0
        private void OnClickSaveWithTransferSyntax(object sender, EventArgs e)
        {
            if (_selected == -1)
            {
                return;
            }

            TransferSyntaxForm tsForm = new TransferSyntaxForm();

            if (tsForm.ShowDialog(this) == DialogResult.OK)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.RestoreDirectory = true;
                if (sfd.ShowDialog(this) == DialogResult.OK)
                {
                    DicomFileFormat ff = new DicomFileFormat();
                    ff.Load(_files[_selected], DicomReadOptions.Default);
                    if (tsForm.SelectedTransferSyntax != null)
                    {
                        ff.ChangeTransferSyntax(tsForm.SelectedTransferSyntax, null);
                    }
                    ff.Save(sfd.FileName, DicomWriteOptions.Default);
                }
            }
        }
Example #5
0
        /// <summary>Creates DICOM image object from file</summary>
        /// <param name="fileName">Source file</param>
        public DicomImage(string fileName)
        {
            DicomFileFormat ff = new DicomFileFormat();

            ff.Load(fileName, DicomReadOptions.Default);
            Load(ff.Dataset);
        }
Example #6
0
        public void UpdateDicomFile(string updateFile, string dicomTag, string newValue)
        {
            try
            {
                DicomFileFormat dicomFile      = new DicomFileFormat();
                DicomTag        updateDicomTag = DicomTag.Parse(dicomTag);

                dicomFile.Load(updateFile, DicomReadOptions.DeferLoadingLargeElements);
                string what = updateDicomTag.Entry.ToString();

                if (updateDicomTag.Entry.ToString().StartsWith("0002"))
                {
                    dicomFile.FileMetaInfo.SetString(updateDicomTag, newValue);
                }

                else
                {
                    dicomFile.Dataset.SetString(updateDicomTag, newValue);
                }

                dicomFile.Dataset.PreloadDeferredBuffers();
                dicomFile.Save(updateFile, DicomWriteOptions.Default);
            }

            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Example #7
0
        private void UpdateImageBox(DcmImageBox imageBox, String filename, int index)
        {
            //try
            //{
            var ff = new DicomFileFormat();

            ff.Load(filename, DicomReadOptions.DefaultWithoutDeferredLoading);
            if (ff.Dataset == null)
            {
                return;
            }

            ff.Dataset.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian, null);

            var pixelData = new DcmPixelData(ff.Dataset);
            var pi        = PhotometricInterpretation.Lookup(pixelData.PhotometricInterpretation);

            // Grayscale only printer?
            if (pi.IsColor && _supportsColorPrinting == false)
            {
                pixelData.Unload();
                return;
            }

            // Color only printer?
            if (pi.IsColor == false && _supportsGrayscalePrinting == false)
            {
                pixelData.Unload();
                return;
            }

            DicomUID        imageBoxSOPClassUID;
            DcmItemSequence seq;
            var             item = new DcmItemSequenceItem();

            pixelData.UpdateDataset(item.Dataset);

            if (pi.IsColor)
            {
                imageBoxSOPClassUID = DicomUID.BasicColorImageBoxSOPClass;
                seq = new DcmItemSequence(DicomTags.BasicColorImageSequence);
            }
            else
            {
                imageBoxSOPClassUID = DicomUID.BasicGrayscaleImageBoxSOPClass;
                seq = new DcmItemSequence(DicomTags.BasicGrayscaleImageSequence);
            }
            seq.AddSequenceItem(item);
            imageBox.Dataset.AddItem(seq);

            pixelData.Unload();

            imageBox.UpdateImageBox(imageBoxSOPClassUID);
            imageBox.ImageBoxPosition = (ushort)index;
            //}
            //catch (Exception)
            //{
            //}
        }
        private int getSeriesNumberFromDcm(string dcmFile)
        {
            int             seriesNumber;
            DicomFileFormat fileRead = new DicomFileFormat();

            fileRead.Load(dcmFile, DicomReadOptions.DeferLoadingLargeElements);
            seriesNumber = Convert.ToInt32(fileRead.Dataset.GetValueString(new DicomTag(DicomConstTags.SeriesNumber)));
            fileRead     = null;
            return(seriesNumber);
        }
Example #9
0
        //extract identifier(UID) from file
        private String getIdentifier(FileStream fs)
        {
            String identifier = String.Empty;

            try
            {
                DicomFileFormat dff = new DicomFileFormat();
                dff.Load(fs, DicomReadOptions.Default);
                identifier = dff.Dataset.GetValueString(DicomTags.SOPInstanceUID);
            }
            catch (Exception e) { Console.WriteLine(e); }

            return(identifier);
        }
Example #10
0
        public List <Dictionary <string, string> > getDicomElementInfo(string fileName, string dirPath)
        {
            try
            {
                DicomFileFormat dff = new DicomFileFormat();
                List <Dictionary <string, string> > elements = new List <Dictionary <string, string> >();
                string loadPath = dirPath + "\\" + fileName;
                dff.Load(loadPath, DicomReadOptions.DeferLoadingLargeElements);
                foreach (DcmItem di in dff.Dataset.Elements)
                {
                    Dictionary <string, string> elementData = new Dictionary <string, string>();
                    elementData.Add("Name", di.Name.ToString());
                    elementData.Add("Tag", di.Tag.ToString());
                    if (dff.Dataset.GetValueString(di.Tag) != "")
                    {
                        elementData.Add("Value", dff.Dataset.GetValueString(di.Tag));
                    }
                    else
                    {
                        elementData.Add("Value", "--Null--");
                    }
                    elements.Add(elementData);
                }

                foreach (DcmItem di in dff.FileMetaInfo.Elements)
                {
                    Dictionary <string, string> elementData = new Dictionary <string, string>();
                    elementData.Add("Name", di.Name.ToString());
                    elementData.Add("Tag", di.Tag.ToString());
                    if (dff.FileMetaInfo.GetValueString(di.Tag) != "")
                    {
                        elementData.Add("Value", dff.FileMetaInfo.GetValueString(di.Tag));
                    }
                    else
                    {
                        elementData.Add("Value", "--Null--");
                    }
                    elements.Add(elementData);
                }

                return(elements);
            }
            catch (Exception e)
            {
                string error = e.ToString();
                return(null);
            }
        }
Example #11
0
        private void ExtractMetaData(FileStream fs, DicomInfo dicom)
        {
            DicomFileFormat dff = new DicomFileFormat();

            dff.Load(fs, DicomReadOptions.Default);
            dicom.patientName    = dff.Dataset.GetValueString(DicomTags.PatientsName);
            dicom.studyUID       = dff.Dataset.GetValueString(DicomTags.StudyInstanceUID);
            dicom.seriesUID      = dff.Dataset.GetValueString(DicomTags.SeriesInstanceUID);
            dicom.imageUID       = dff.Dataset.GetValueString(DicomTags.SOPInstanceUID);
            dicom.sex            = dff.Dataset.GetValueString(DicomTags.PatientsSex);
            dicom.pBday          = dff.Dataset.GetValueString(DicomTags.PatientsBirthDate);
            dicom.age            = dff.Dataset.GetValueString(DicomTags.PatientsAge);
            dicom.imgNumber      = dff.Dataset.GetValueString(DicomTags.InstanceNumber);
            dicom.modality       = dff.Dataset.GetValueString(DicomTags.Modality);
            dicom.bodyPart       = dff.Dataset.GetValueString(DicomTags.BodyPartExamined);
            dicom.studyDesc      = dff.Dataset.GetValueString(DicomTags.StudyDescription);
            dicom.seriesDesc     = dff.Dataset.GetValueString(DicomTags.SeriesDescription);
            dicom.sliceThickness = dff.Dataset.GetValueString(DicomTags.SliceThickness);
        }
Example #12
0
        private static void CheckDICOMFile(FileInfo FI, TextWriter output, List <DicomTag> DicomTagsToCheck, Dictionary <DicomTag, List <String> > tagTovalues)
        {
            //output.WriteLine("Checking: " + FI.FullName);

            var dcmFile     = new DicomFileFormat();
            var dcmFileName = FI.FullName;

            if (dcmFile.Load(dcmFileName, DicomReadOptions.Default) == DicomReadStatus.Success)
            {
                var sb = new StringBuilder();

                if (dcmFile.Dataset != null)
                {
                    foreach (var DT in DicomTagsToCheck)
                    {
                        var Element = dcmFile.Dataset.GetElement(DT);

                        if (Element != null)
                        {
                            var ElementValue = Element.GetValueString();
                            if (ElementValue != null && ElementValue.Length != 0)
                            {
                                //output.WriteLine(Element + " = " + ElementValue);
                                addValue(tagTovalues, DT, ElementValue);
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("dcm2txt: Missing dataset in DICOM file '{0}'.", dcmFileName);

                    return;
                }

                //output.WriteLine(sb.ToString());
            }
            else
            {
                Console.WriteLine("dcm2txt: '{0}' does not appear to be a DICOM file.", dcmFileName);
                return;
            }
        }
Example #13
0
        private void LoadButtonClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = Resources["dicomFileDialog"] as OpenFileDialog;

            if (dlg != null && dlg.ShowDialog().GetValueOrDefault())
            {
                using (var memStream = new MemoryStream())
                {
                    using (var fileStream = dlg.OpenFile())
                    {
                        fileStream.CopyTo(memStream);
                    }

                    var ff = new DicomFileFormat();
                    ff.Load(memStream, DicomReadOptions.Default);
                    DumpDisplayDataset(dlg.FileName, ff.Dataset);
                }
            }
        }
Example #14
0
        public void anonymizeDicomFile(String dicomFile, int fileCount)
        {
            try
            {
                fileEdit.Load(dicomFile, DicomReadOptions.DeferLoadingLargeElements);

                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.PatientsName), anonymizeData.patientName());
                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.PatientsBirthDate), newData.patientDOB());
                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.PatientID), newData.patientID());

                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.StudyDate), newData.studyDate());
                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.StudyDescription), newData.studyDescription());
                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.StudyInstanceUID), newStudyInstanceId); // major confusion on this; I may need to do SOPId too and possibly Study ID
                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.SeriesInstanceUID), newSessionIdString);
                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.SOPInstanceUID), newInstanceIdString);

                fileEdit.Dataset.SetString(new DicomTag(DicomConstTags.AccessionNumber), newData.accessionNumber());
                fileEdit.FileMetaInfo.SetString(new DicomTag(DicomConstTags.MediaStorageSOPInstanceUID), newInstanceIdString);
            }
        }
Example #15
0
        private void fileNameButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dlg = Resources["dicomFileDialog"] as OpenFileDialog;

            if (dlg != null && dlg.ShowDialog().GetValueOrDefault())
            {
                using (var memStream = new MemoryStream())
                {
                    using (var fileStream = dlg.File.OpenRead())
                    {
                        fileStream.CopyTo(memStream);
                    }

                    DicomFileFormat ff = new DicomFileFormat();
                    ff.Load(memStream, DicomReadOptions.Default);
                    if (ff.Dataset != null)
                    {
                        StringBuilder sb = new StringBuilder();
                        ff.Dataset.Dump(sb, String.Empty, DicomDumpOptions.Default);
                        RawDump = sb.ToString();

                        var xmlDoc    = XDicom.ToXML(ff.Dataset, XDicomOptions.None);
                        var txtWriter = new StringWriter();
                        xmlDoc.Save(txtWriter);
                        XmlDump = txtWriter.ToString();

                        DicomImage = ff.Dataset.Contains(DicomTags.PixelData)
                                         ? GetImageSource(ff.Dataset)
                                         : null;
                    }
                    else
                    {
                        RawDump    = XmlDump = String.Format(Resources["noDicomFileDataMsg"].ToString(), dlg.File.Name);
                        DicomImage = null;
                    }
                }
                UpdateLog();
            }
        }
Example #16
0
        private bool LoadFile(string file)
        {
            bool            success = false;
            DicomFileFormat ff      = new DicomFileFormat();

            try {
                ClearDump();

                ff.Load(file, DicomReadOptions.Default | DicomReadOptions.KeepGroupLengths);

                success = true;
            }
            catch (Exception e) {
                MessageBox.Show(e.Message + "\n\n" + file, "Error parsing file!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            treeDump.Model = LoadFileFormat(ff);
            treeDump.ExpandAll();

            if (success)
            {
                if (ff.Dataset.Contains(DicomTags.PixelData))
                {
                    tsbViewImage.Enabled     = true;
                    tsbExtractPixels.Enabled = true;
                    tsbPixelDataMD5.Enabled  = true;
                }
                tsbSaveTS.Enabled = true;
            }
            else
            {
                tsbViewImage.Enabled     = false;
                tsbExtractPixels.Enabled = false;
                tsbSaveTS.Enabled        = false;
                tsbPixelDataMD5.Enabled  = false;
            }

            return(success);
        }
Example #17
0
        private void OnClickExtractPixels(object sender, EventArgs e)
        {
            if (_selected == -1)
            {
                return;
            }

            try {
                DicomFileFormat ff = new DicomFileFormat();
                ff.Load(_files[_selected], DicomReadOptions.Default |
                        DicomReadOptions.KeepGroupLengths |
                        DicomReadOptions.DeferLoadingLargeElements |
                        DicomReadOptions.DeferLoadingPixelData);

                DcmPixelData pixels = new DcmPixelData(ff.Dataset);

                if (pixels.NumberOfFrames == 0)
                {
                    return;
                }
                else if (pixels.NumberOfFrames >= 1)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.RestoreDirectory = true;
                    if (sfd.ShowDialog(this) == DialogResult.OK)
                    {
                        byte[] data = pixels.GetFrameDataU8(0);
                        File.WriteAllBytes(sfd.FileName, data);
                    }
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
            catch {
            }
        }
Example #18
0
        private static void Main(string[] args)
        {
            if (args.Length == 0 || args.Length > 2 ||
                (args.Length == 2 && args[0].Equals(args[1], StringComparison.InvariantCultureIgnoreCase)))
            {
                Console.WriteLine("usage: dcm2txt dcmfile-in [txtfile-out]");
                return;
            }

            var dcmFileName = args[0];

            if (!File.Exists(dcmFileName))
            {
                Console.WriteLine("dcm2txt: Specified DICOM file '{0}' does not exist or cannot be accessed.",
                                  dcmFileName);
                return;
            }

            if (File.Exists("dicom.dic"))
            {
                DcmDictionary.ImportDictionary("dicom.dic");
            }
            else
            {
                DcmDictionary.LoadInternalDictionary();
            }

            if (File.Exists("private.dic"))
            {
                DcmDictionary.ImportDictionary("private.dic");
            }

            string dump;

            try
            {
                var dcmFile = new DicomFileFormat();
                if (dcmFile.Load(dcmFileName, DicomReadOptions.Default) == DicomReadStatus.Success)
                {
                    var sb = new StringBuilder();

                    if (dcmFile.FileMetaInfo != null)
                    {
                        dcmFile.FileMetaInfo.Dump(sb, String.Empty, DicomDumpOptions.None);
                    }

                    if (dcmFile.Dataset != null)
                    {
                        dcmFile.Dataset.Dump(sb, String.Empty, DicomDumpOptions.None);
                    }
                    else
                    {
                        Console.WriteLine("dcm2txt: Missing dataset in DICOM file '{0}'.", dcmFileName);
                        return;
                    }
                    dump = sb.ToString();
                }
                else
                {
                    Console.WriteLine("dcm2txt: '{0}' does not appear to be a DICOM file.", dcmFileName);
                    return;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("dcm2txt: Dumping DICOM file to text failed, reason: {0}.", e.Message);
                return;
            }

            try
            {
                if (args.Length == 2)
                {
                    var txtFileName = args[1];
                    File.WriteAllText(txtFileName, dump);
                }
                else
                {
                    Console.Write(dump);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("dcm2txt: Writing DICOM dump to file/console failed, reason: {0}.", e.Message);
            }
        }
Example #19
0
        /// <summary>
        /// Loads the DICOM file and changes the transfer syntax if needed. (Internal)
        /// </summary>
        /// <param name="client">C-Store Client</param>
        public void Load(CStoreClient client)
        {
            if (_loaded)
            {
                return;
            }

            try {
                DicomTransferSyntax tx = null;

                foreach (DcmPresContext pc in client.Associate.GetPresentationContexts())
                {
                    if (pc.Result == DcmPresContextResult.Accept && pc.AbstractSyntax == _sopClass)
                    {
                        tx = pc.AcceptedTransferSyntax;
                        break;
                    }
                }

                if (tx == null)
                {
                    throw new DicomNetworkException("No accepted presentation contexts for abstract syntax: " + _sopClass.Description);
                }

                // Possible to stream from file?
                if (!client.DisableFileStreaming && tx == TransferSyntax)
                {
                    using (FileStream fs = DicomFileFormat.GetDatasetStream(_fileName)) {
                        _datasetSize = Convert.ToUInt32(fs.Length - fs.Position);
                        fs.Close();
                    }
                    return;
                }

                DcmCodecParameters codecParams = null;
                if (tx == client.PreferredTransferSyntax)
                {
                    codecParams = client.PreferredTransferSyntaxParams;
                }

                DicomFileFormat ff = new DicomFileFormat();
                ff.Load(FileName, DicomReadOptions.DefaultWithoutDeferredLoading);

                if (_originalTransferSyntax != tx)
                {
                    if (_originalTransferSyntax.IsEncapsulated)
                    {
                        // Dataset is compressed... decompress
                        try {
                            ff.ChangeTransferSytnax(DicomTransferSyntax.ExplicitVRLittleEndian, null);
                        }
                        catch {
                            client.Log.Error("{0} -> Unable to change transfer syntax:\n\tclass: {1}\n\told: {2}\n\tnew: {3}\n\treason: {4}\n\tcodecs: {5} - {6}",
                                             client.LogID, SOPClassUID.Description, _originalTransferSyntax, DicomTransferSyntax.ExplicitVRLittleEndian,
#if DEBUG
                                             HasError ? "Unknown" : Error.ToString(),
#else
                                             HasError ? "Unknown" : Error.Message,
#endif
                                             DicomCodec.HasCodec(_originalTransferSyntax), DicomCodec.HasCodec(DicomTransferSyntax.ExplicitVRLittleEndian));
                            throw;
                        }
                    }

                    if (tx.IsEncapsulated)
                    {
                        // Dataset needs to be compressed
                        try {
                            ff.ChangeTransferSytnax(tx, codecParams);
                        }
                        catch {
                            client.Log.Error("{0} -> Unable to change transfer syntax:\n\tclass: {1}\n\told: {2}\n\tnew: {3}\n\treason: {4}\n\tcodecs: {5} - {6}",
                                             client.LogID, SOPClassUID.Description, ff.Dataset.InternalTransferSyntax, tx,
#if DEBUG
                                             HasError ? "Unknown" : Error.ToString(),
#else
                                             HasError ? "Unknown" : Error.Message,
#endif
                                             DicomCodec.HasCodec(ff.Dataset.InternalTransferSyntax), DicomCodec.HasCodec(tx));
                            throw;
                        }
                    }
                }

                _dataset        = ff.Dataset;
                _datasetSize    = _dataset.CalculateWriteLength(tx, DicomWriteOptions.Default);
                _transferSyntax = tx;
            }
            catch (Exception e) {
                _dataset        = null;
                _transferSyntax = _originalTransferSyntax;
                _status         = DcmStatus.ProcessingFailure;
                _exception      = e;
            }
            finally {
                _loaded = true;
            }
        }