Esempio n. 1
0
        /// <summary>
        /// Load color look-up table from file.
        /// </summary>
        /// <param name="path">File name.</param>
        /// <returns>Loaded color look-up table.</returns>
        public static Color32[] LoadLUT(string path)
        {
            try
            {
                byte[] data;
                using (var stream = IOManager.CreateFileReference(path).OpenRead())
                {
                    var length = (int)stream.Length;
                    if (length != (256 * 3))
                    {
                        return(null);
                    }

                    data = new byte[length];
                    stream.Read(data, 0, length);
                }

                var lut = new Color32[256];
                for (var i = 0; i < 256; i++)
                {
                    lut[i] = new Color32(0xff, data[i], data[i + 256], data[i + 512]);
                }

                return(lut);
            }
            catch
            {
                return(null);
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Asynchronously read DICOM Directory.
        /// </summary>
        /// <param name="fileName">File name.</param>
        /// <param name="fallbackEncoding">Encoding to apply if it cannot be identified from DICOM directory.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns>Awaitable <see cref="DicomDirectory"/> instance.</returns>
        public static new async Task <DicomDirectory> OpenAsync(string fileName, Encoding fallbackEncoding, Func <ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException(nameof(fallbackEncoding));
            }
            var df = new DicomDirectory();

            try
            {
                df.File = IOManager.CreateFileReference(fileName);

                using (var source = new FileByteSource(df.File))
                {
                    var reader      = new DicomFileReader();
                    var dirObserver = new DicomDirectoryReaderObserver(df.Dataset);

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

                    return(FinalizeDicomDirectoryLoad(df, reader, dirObserver, result));
                }
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Save color look-up table to file.
        /// </summary>
        /// <param name="path">File name.</param>
        /// <param name="lut">Look-up table to save.</param>
        public static void SaveLUT(string path, Color32[] lut)
        {
            if (lut.Length != 256)
            {
                return;
            }

            var file = IOManager.CreateFileReference(path);

            using (var fs = file.Create())
            {
                for (var i = 0; i < 256; i++)
                {
                    fs.WriteByte(lut[i].R);
                }
                for (var i = 0; i < 256; i++)
                {
                    fs.WriteByte(lut[i].G);
                }
                for (var i = 0; i < 256; i++)
                {
                    fs.WriteByte(lut[i].B);
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Asynchronously read DICOM Directory.
        /// </summary>
        /// <param name="fileName">File name.</param>
        /// <param name="fallbackEncoding">Encoding to apply if it cannot be identified from DICOM directory.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns>Awaitable <see cref="DicomDirectory"/> instance.</returns>
        public static new async Task <DicomDirectory> OpenAsync(string fileName, Encoding fallbackEncoding, Func <ParseState, bool> stop = null)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException("fallbackEncoding");
            }
            var df = new DicomDirectory();

            // reset datasets
            df.FileMetaInfo.Clear();
            df.Dataset.Clear();

            try
            {
                df.File = IOManager.CreateFileReference(fileName);

                using (var source = new FileByteSource(df.File))
                {
                    var reader = new DicomFileReader();

                    var datasetObserver = new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding);
                    var dirObserver     = new DicomDirectoryReaderObserver(df.Dataset);

                    var result =
                        await
                        reader.ReadAsync(
                            source,
                            new DicomDatasetReaderObserver(df.FileMetaInfo),
                            new DicomReaderMultiObserver(datasetObserver, dirObserver),
                            stop).ConfigureAwait(false);

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

                    df.Format = reader.FileFormat;

                    df.Dataset.InternalTransferSyntax = reader.Syntax;

                    df._directoryRecordSequence = df.Dataset.Get <DicomSequence>(DicomTag.DirectoryRecordSequence);
                    df.RootDirectoryRecord      = dirObserver.BuildDirectoryRecords();

                    return(df);
                }
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Load DICOM dictionary data from file.
        /// </summary>
        /// <param name="file">File name.</param>
        /// <param name="format">File format.</param>
        public void Load(string file, DicomDictionaryFormat format)
        {
            using (var fs = IOManager.CreateFileReference(file).OpenRead())
            {
                var s = fs;
                if (file.EndsWith(".gz"))
                {
                    s = new GZipStream(s, CompressionMode.Decompress);
                }

                var reader = new DicomDictionaryReader(this, format, s);
                reader.Process();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Saves PDU to file
        /// </summary>
        /// <param name="file">Filename</param>
        public void Save(string file)
        {
            var f = IOManager.CreateFileReference(file);
            var d = f.Directory;

            if (!d.Exists)
            {
                d.Create();
            }
            using (var fs = f.OpenWrite())
            {
                WritePDU(fs);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Save to file asynchronously.
        /// </summary>
        /// <param name="fileName">Name of file.</param>
        /// <param name="options">Options to apply during writing.</param>
        /// <returns>Awaitable <see cref="Task"/>.</returns>
        public async Task SaveAsync(string fileName, DicomWriteOptions options = null)
        {
            this.PreprocessFileMetaInformation();

            this.File = IOManager.CreateFileReference(fileName);
            this.File.Delete();

            this.OnSave();

            using (var target = new FileByteTarget(this.File))
            {
                var writer = new DicomFileWriter(options);
                await writer.WriteAsync(target, this.FileMetaInfo, this.Dataset).ConfigureAwait(false);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Save DICOM file.
        /// </summary>
        /// <param name="fileName">File name.</param>
        /// <param name="options">Options to apply during writing.</param>
        public void Save(string fileName, DicomWriteOptions options = null)
        {
            this.PreprocessFileMetaInformation();

            this.File = IOManager.CreateFileReference(fileName);
            this.File.Delete();

            this.OnSave();

            using (var target = new FileByteTarget(this.File))
            {
                var writer = new DicomFileWriter(options);
                writer.Write(target, this.FileMetaInfo, this.Dataset);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Save the image box contents to file.
        /// </summary>
        /// <param name="imageBoxFile">Name of the image box file.</param>
        public void Save(string imageBoxFile)
        {
            var imageBoxDicomFile = imageBoxFile + ".dcm";
            var imageBoxTextFile  = imageBoxFile + ".txt";

            using (var stream = IOManager.CreateFileReference(imageBoxTextFile).Create())
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(this.WriteToString());
                }

            var file = new DicomFile(this);

            file.Save(imageBoxDicomFile);
        }
Esempio n. 10
0
 /// <summary>
 /// Test if file has a valid preamble and DICOM 3.0 header.
 /// </summary>
 /// <param name="path">Path to file</param>
 /// <returns>True if valid DICOM 3.0 file header is detected.</returns>
 public static bool HasValidHeader(string path)
 {
     try
     {
         var file = IOManager.CreateFileReference(path);
         using (var fs = file.OpenRead())
         {
             fs.Seek(128, SeekOrigin.Begin);
             return(fs.ReadByte() == 'D' && fs.ReadByte() == 'I' && fs.ReadByte() == 'C' && fs.ReadByte() == 'M');
         }
     }
     catch
     {
         return(false);
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Asynchronously reads the specified filename and returns a DicomFile object.  Note that the values for large
        /// DICOM elements (e.g. PixelData) are read in "on demand" to conserve memory.  Large DICOM elements
        /// are determined by their size in bytes - see the default value for this in the FileByteSource._largeObjectSize
        /// </summary>
        /// <param name="fileName">The filename of the DICOM file</param>
        /// <param name="fallbackEncoding">Encoding to apply when attribute Specific Character Set is not available.</param>
        /// <param name="stop">Stop criterion in dataset.</param>
        /// <returns>Awaitable <see cref="DicomFile"/> instance.</returns>
        public static async Task <DicomFile> OpenAsync(string fileName, Encoding fallbackEncoding, Func <ParseState, bool> stop = null, FileReadOption readOption = FileReadOption.Default)
        {
            if (fallbackEncoding == null)
            {
                throw new ArgumentNullException(nameof(fallbackEncoding));
            }
            var df = new DicomFile();

            try
            {
                df.File = IOManager.CreateFileReference(fileName);

                using (var unvalidated = new UnvalidatedScope(df.Dataset))
                    using (var source = new FileByteSource(df.File, readOption))
                    {
                        var reader = new DicomFileReader();
                        var result =
                            await
                            reader.ReadAsync(
                                source,
                                new DicomDatasetReaderObserver(df.FileMetaInfo),
                                new DicomDatasetReaderObserver(df.Dataset, fallbackEncoding),
                                stop).ConfigureAwait(false);

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

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

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

            try
            {
                df.File = IOManager.CreateFileReference(fileName);

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

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

                    df.Format = reader.FileFormat;

                    df.Dataset.InternalTransferSyntax = reader.Syntax;

                    return(df);
                }
            }
            catch (Exception e)
            {
                throw new DicomFileException(df, e.Message, e);
            }
        }
Esempio n. 13
0
        public void Write_SimpleFile_CommentMaintained()
        {
            lock (this.locker)
            {
                const string fileName = @".\Test Data\dicomfilewriter_write.dcm";
                var          file     = IOManager.CreateFileReference(fileName);

                using (var target = new FileByteTarget(file))
                {
                    var writer = new DicomFileWriter(new DicomWriteOptions());
                    writer.Write(target, this.metaInfo, this.dataset);
                }

                var expected = Comment;
                var readFile = DicomFile.Open(fileName);
                var actual   = readFile.Dataset.Get <string>(DoseCommentTag);
                Assert.Equal(expected, actual);

                var syntax = readFile.FileMetaInfo.TransferSyntax;
                Assert.Equal(DicomTransferSyntax.JPEG2000Lossless, syntax);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Save the contents of the film box.
        /// </summary>
        /// <param name="filmBoxFolder">Folder in which to save the film box contents.</param>
        public void Save(string filmBoxFolder)
        {
            var filmBoxDicomFile = string.Format(@"{0}\FilmBox.dcm", filmBoxFolder);
            var filmBoxTextFile  = string.Format(@"{0}\FilmBox.txt", filmBoxFolder);
            var file             = new DicomFile(this);

            file.Save(filmBoxDicomFile);

            using (var stream = IOManager.CreateFileReference(filmBoxTextFile).Create())
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(this.WriteToString());
                }

            var imageBoxFolderInfo = IOManager.CreateDirectoryReference(string.Format(@"{0}\Images", filmBoxFolder));

            imageBoxFolderInfo.Create();
            for (int i = 0; i < this.BasicImageBoxes.Count; i++)
            {
                var imageBox = this.BasicImageBoxes[i];
                imageBox.Save(string.Format(@"{0}\I{1:000000}", imageBoxFolderInfo.Name, i + 1));
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Save to file asynchronously.
        /// </summary>
        /// <param name="fileName">Name of file.</param>
        /// <returns>Awaitable <see cref="Task"/>.</returns>
        public async Task SaveAsync(string fileName)
        {
            if (this.Format == DicomFileFormat.ACRNEMA1 || this.Format == DicomFileFormat.ACRNEMA2)
            {
                throw new DicomFileException(this, "Unable to save ACR-NEMA file");
            }

            if (this.Format == DicomFileFormat.DICOM3NoFileMetaInfo)
            {
                // create file meta information from dataset
                this.FileMetaInfo = new DicomFileMetaInformation(this.Dataset);
            }

            this.File = IOManager.CreateFileReference(fileName);
            this.File.Delete();

            this.OnSave();

            using (var target = new FileByteTarget(this.File))
            {
                var writer = new DicomFileWriter(DicomWriteOptions.Default);
                await writer.WriteAsync(target, this.FileMetaInfo, this.Dataset).ConfigureAwait(false);
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Save DICOM file.
        /// </summary>
        /// <param name="fileName">File name.</param>
        public void Save(string fileName)
        {
            if (Format == DicomFileFormat.ACRNEMA1 || Format == DicomFileFormat.ACRNEMA2)
            {
                throw new DicomFileException(this, "Unable to save ACR-NEMA file");
            }

            if (Format == DicomFileFormat.DICOM3NoFileMetaInfo)
            {
                // create file meta information from dataset
                FileMetaInfo = new DicomFileMetaInformation(Dataset);
            }

            File = IOManager.CreateFileReference(fileName);
            File.Delete();

            OnSave();

            using (var target = new FileByteTarget(File))
            {
                DicomFileWriter writer = new DicomFileWriter(DicomWriteOptions.Default);
                writer.Write(target, FileMetaInfo, Dataset);
            }
        }