private void _sendImage(PSImage image, Stream outputStream, BinaryWriter writer) { var transferSyntax = TransferSyntaxes.Lookup(image.TransferSyntaxID); if (transferSyntax.Compression != DICOMSharp.Data.Compression.CompressionInfo.None) { // Need to decompress var data = new DICOMData(); data.ParseFile(PSUtils.GetParsedFilePath(image.Path), true, PSUtils.GetLogger()); data.Uncompress(); var memStream = new MemoryStream(); data.WriteToStreamAsPart10File(memStream, PSUtils.GetLogger()); writer.Write((UInt32)(memStream.Length + 4)); memStream.Position = 0; memStream.CopyTo(outputStream); } else { // Write the file out directly. var fileInfo = new FileInfo(PSUtils.GetParsedFilePath(image.Path)); var size = fileInfo.Length; writer.Write((UInt32)(size + 4)); fileInfo.OpenRead().CopyTo(outputStream); } }
public static void RoundTripAndRender() { foreach (FileInfo fi in new DirectoryInfo("..\\CompressionSamples").GetFiles("*.dcm")) { Console.WriteLine("Compression Test -- Filename: " + fi.Name); DICOMData data = new DICOMData(); data.ParseFile(fi.FullName, true, new NullLogger()); TransferSyntax syntax = data.TransferSyntax; int compressedLength = (int)data[DICOMTags.PixelData].GetDataLength(false); data.Uncompress(); Image testImage = DICOMQuickRenderer.QuickRender(data, 0); Assert.IsNotNull(testImage); int uncompressedLength = (int)data[DICOMTags.PixelData].GetDataLength(false); Assert.IsTrue(uncompressedLength > compressedLength); if (CompressionWorker.SupportsCompression(syntax.Compression)) { data.ChangeTransferSyntax(syntax); int recompressedLength = (int)data[DICOMTags.PixelData].GetDataLength(false); Assert.IsTrue(recompressedLength < uncompressedLength); } //data.WriteFile(fi.FullName.Replace(".dcm", "_un.dcm")); } }
private void openToolStripMenuItem_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { DICOMData loadedData = new DICOMData(); loadedData.ParseFile(openFileDialog1.FileName, true, new NullLogger()); loadedData.Uncompress(); if (loadedData.Elements.ContainsKey(DICOMTags.PixelData)) { viewer.AddImage(loadedData); } } }
static void TestThumbnails() { foreach (FileInfo fi in new DirectoryInfo("..\\CompressionSamples").GetFiles("*.dcm")) //foreach (FileInfo fi in new DirectoryInfo("..\\CompressionSamples").GetFiles("JPEG-LS Lossless.dcm")) { Console.WriteLine("Compression Test -- Filename: " + fi.Name); DICOMData data = new DICOMData(); data.ParseFile(fi.FullName, true, new NullLogger()); //data.Uncompress(); //data.WriteFile(fi.FullName.Replace(".dcm", "_un.dcm")); Image testImage = DICOMQuickRenderer.QuickRender(data, 0); testImage.Save(fi.FullName.Replace(".dcm", ".png"), ImageFormat.Png); } }
private void LoadFile(string FName) { CurFName = FName; CurDCM = new DICOMData(); CurDCM.ParseFile(CurFName, true, new NullLogger()); //StringBuilder builder = new StringBuilder(); //builder.Append("[\r\n"); //byte[] data = (byte[])CurDCM.Elements[DICOMTags.PixelData].Data; //for (int i=0; i<data.Length; i++) //{ // builder.Append(data[i]); // if (i < data.Length-1) builder.Append(","); // if ((i & 255) == 0) builder.Append("\r\n"); //} //builder.Append("]\r\n"); //File.WriteAllText(@"c:\src\test.json", builder.ToString()); RefreshView(); }
/// <summary> /// Call this function to recursively look through a directory and try to find all valid DICOM files from /// that directory. When it finds one, it will load it (without the image data loaded, for speed reasons) /// and pass it through to the <see cref="ImageAddedHandler"/> callback. /// </summary> /// <param name="baseDir">The directory to start searching in.</param> /// <param name="handler">The callback function called with every found/loaded image.</param> /// <param name="logger">The logger to use for error/info.</param> /// <param name="token">A cancellation token to abort the import.</param> public static void ParseAndLoadImagesFromDirectoryRecursively(DirectoryInfo baseDir, ImageAddedHandler handler, ILogger logger, CancellationToken token) { foreach (DirectoryInfo di2 in baseDir.GetDirectories()) { if (token.IsCancellationRequested) { return; } ParseAndLoadImagesFromDirectoryRecursively(di2, handler, logger, token); } foreach (FileInfo fi in baseDir.GetFiles()) { if (token.IsCancellationRequested) { return; } try { DICOMData data = new DICOMData(); if (data.ParseFile(fi.FullName, false, logger)) { if (token.IsCancellationRequested) { return; } handler(data, fi.FullName); } } catch { } } }
private TaskInfo ImportFromPath(string basePath) { var taskInfo = new TaskInfo() { Token = new CancellationTokenSource() }; taskInfo.Task = Task.Run(() => { taskInfo.Token.Token.ThrowIfCancellationRequested(); this._logger.Log(LogLevel.Info, "Importing from Path: " + basePath); DirectoryInfo di = new DirectoryInfo(basePath); if (!di.Exists) { this._logger.Log(LogLevel.Error, "Directory not found!"); return; } else { FileUtil.ImageAddedHandler callback = (DICOMData data, string path) => { taskInfo.ProgressCount++; taskInfo.ProgressTotal++; if (!data.Elements.ContainsKey(DICOMTags.PixelData) && !this._settings.StoreMetadataOnlyFiles) { this._logger.Log(LogLevel.Info, "Data set has no image data (only metadata). Metadata storing is disabled, so image will not be persisted."); return; } if (this._settings.AutoDecompress && data.TransferSyntax.Compression != DICOMSharp.Data.Compression.CompressionInfo.None) { this._logger.Log(LogLevel.Info, "Image is compressed, decompressing in place!"); DICOMData fullData = new DICOMData(); if (fullData.ParseFile(path, true, this._logger)) { if (fullData.Uncompress()) { if (fullData.WriteFile(path, this._logger)) { // Stuff the new decompressed and written file into the DB instead data = fullData; } else { this._logger.Log(LogLevel.Warning, "Failed to write out decompressed file! Storing compressed image."); } } else { this._logger.Log(LogLevel.Warning, "Image decompression failed! Storing compressed image."); } } else { this._logger.Log(LogLevel.Warning, "Couldn't parse full image data! Storing compressed image."); } } this._db.PersistImage(data, path, path); }; FileUtil.ParseAndLoadImagesFromDirectoryRecursively(di, callback, this._logger, taskInfo.Token.Token); } this._logger.Log(LogLevel.Info, "Done Importing from Path: " + basePath); }, taskInfo.Token.Token); return(taskInfo); }
private void SendNextImage() { DICOMData data = null; while (sendQueue.Count > 0) { var nextImg = sendQueue.Dequeue(); try { data = nextImg.DicomData; if (data == null) { if (!File.Exists(nextImg.FilePath)) { logger.Log(LogLevel.Error, "File doesn't exist: " + nextImg.FilePath); failed++; if (SendUpdate != null) { SendUpdate(this, (ushort)sendQueue.Count, completed, warned, failed); } continue; } data = new DICOMData(); if (!data.ParseFile(nextImg.FilePath, true, logger)) { failed++; if (SendUpdate != null) { SendUpdate(this, (ushort)sendQueue.Count, completed, warned, failed); } continue; } } // See if anyone wants to do any work to it if (PreSendImage != null) { PreSendImage(this, data); } AbstractSyntax absSyntax = AbstractSyntaxes.CTImageStorage; if (data.Elements.ContainsKey(DICOMTags.SOPClassUID)) { absSyntax = AbstractSyntaxes.Lookup((string)data[DICOMTags.SOPClassUID].Data); } conn.SendCSTORERQ(data, absSyntax, CommandPriority.Medium, moveInitiatorAETitle, moveMessageID); } catch (Exception e) { logger.Log(LogLevel.Error, "Unknown error encountered in DICOMSender.SendNextImage: " + e.Message); failed++; if (SendUpdate != null) { SendUpdate(this, (ushort)sendQueue.Count, completed, warned, failed); } } return; } conn.SendReleaseRQ(); }