/// <summary> /// Prints an image box onto the specified graphics. /// </summary> /// <param name="imageBox">Image box to print.</param> /// <param name="graphics">Graphics in which image box should be contained.</param> /// <param name="box">Rectangle within which the image box should be contained.</param> /// <param name="imageResolution">Image resolution.</param> public static void Print(this ImageBox imageBox, Graphics graphics, RectF box, int imageResolution) { var state = graphics.Save(); FillBox(imageBox.FilmBox, box, graphics); var boxCopy = box; if (imageBox.FilmBox.Trim == "YES") { boxCopy.Inflate(-BORDER, -BORDER); } if (imageBox.ImageSequence != null && imageBox.ImageSequence.Contains(DicomTag.PixelData)) { Image bitmap = null; try { var image = new DicomImage(imageBox.ImageSequence); var frame = image.RenderImage().As<Image>(); bitmap = frame; DrawBitmap(graphics, boxCopy, bitmap, imageResolution, imageBox.FilmBox.EmptyImageDensity); } finally { if (bitmap != null) { bitmap.Dispose(); } } } graphics.Restore(state); }
public void RotateAndFlipImage() { DicomFile myDicomFile = DicomFile.Open(@"Test Data\CR-MONO1-10-chest"); var myDicomImage = new DicomImage(myDicomFile.Dataset); IImage myImg = myDicomImage.RenderImage(0); myImg.Render(3, true, true, 0); }
protected override void OnLoad(EventArgs e) { // execute on ThreadPool to avoid STA WaitHandle.WaitAll exception ThreadPool.QueueUserWorkItem(delegate(object s) { DicomImage image = new DicomImage(_fileName); Invoke(new WaitCallback(DisplayImage), image.RenderImage()); }); }
public void DicomJpegLosses_DecodingAvailable(string filename) { ImageManager.SetImplementation(RawImageManager.Instance); var file = DicomFile.Open(@".\Test Data\" + filename, FileReadOption.ReadAll); var dcmImage = new DicomImage(file.Dataset); var image = dcmImage.RenderImage(); Assert.NotNull(image); }
public void RenderImage_ColorPaletteWithOffset(string filename) { lock (_lock) { ImageManager.SetImplementation(WinFormsImageManager.Instance); var file = new DicomImage(@".\Test Data\" + filename); var image = file.RenderImage(0); Assert.IsAssignableFrom <Bitmap>(image.As <Bitmap>()); } }
public void RenderImage_ColorPalette() { lock (_lock) { ImageManager.SetImplementation(WinFormsImageManager.Instance); var file = new DicomImage(@".\Test Data\10200904.dcm"); var image = file.RenderImage(0); Assert.IsAssignableFrom <Bitmap>(image.As <Bitmap>()); } }
public void TestActualRendering() { ImageManager.SetImplementation(new ImageSharpImageManager()); var dcmImage = new DicomImage(@"Test Data\CR-MONO1-10-chest"); var image = dcmImage.RenderImage(); Assert.IsAssignableFrom <Image <Bgra32> >(image.AsSharpImage()); var sharpImage = image.AsSharpImage(); Assert.Equal(dcmImage.Width, sharpImage.Width); Assert.Equal(dcmImage.Height, sharpImage.Height); }
public void ManipulatedImage_MultithreadedAccess_ShouldNotThrow() { lock (_lock) { ImageManager.SetImplementation(WinFormsImageManager.Instance); var image = new DicomImage(@".\Test Data\CT-MONO2-16-ankle"); var exception = Record.Exception(() => { Parallel.For(0, 1000, i => { image.RenderImage().AsBitmap(); image.Scale = 0.999; }); }); Assert.Null(exception); } }
private static void Main(string[] args) { // Initialize log manager. LogManager.SetImplementation(ConsoleLogManager.Instance); var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); var printJob = new PrintJob("DICOM PRINT JOB") { RemoteAddress = "localhost", RemotePort = 8000, CallingAE = "PRINTSCU", CalledAE = "PRINTSCP" }; printJob.StartFilmBox("STANDARD\\1,1", "PORTRAIT", "A4"); printJob.FilmSession.IsColor = false; //set to true to print in color //greyscale var dicomImage = new DicomImage(@"Data\1.3.51.5155.1353.20020423.1100947.1.0.0.dcm"); //color //var dicomImage = new DicomImage(@"Data\US-RGB-8-epicard.dcm"); var bitmap = dicomImage.RenderImage().As<Bitmap>(); printJob.AddImage(bitmap, 0); bitmap.Dispose(); printJob.EndFilmBox(); printJob.Print(); stopwatch.Stop(); Console.WriteLine(); Console.WriteLine(stopwatch.Elapsed); }
private void button1_Click(object sender, EventArgs e) { try { var printJob = new PrintJob("DICOM PRINT JOB") { RemoteAddress = spu.RemoteAddress, RemotePort = spu.RemotePort, CallingAE = spu.CallingAE, CalledAE = spu.CalledAE }; printJob.StartFilmBox("STANDARD\\1,1", "PORTRAIT", "A4"); printJob.FilmSession.IsColor = checkBox1.Checked; //set to true to print in color //greyscale var dicomImage = new DicomImage(textBox1.Text); //color //var dicomImage = new DicomImage(@"Data\US-RGB-8-epicard.dcm"); var bitmap = dicomImage.RenderImage() as System.Drawing.Bitmap; printJob.AddImage(bitmap, 0); bitmap.Dispose(); printJob.EndFilmBox(); printJob.Print(); } catch (System.Exception ex) { Helper.msgbox_info("打印失败", ex.Message + Environment.NewLine + ex.StackTrace, this); } }
public void DrawImageBox(ImageBox imgBox, Graphics graphics, RectangleF box, int imageResolution) { var imageSequence = imgBox.ImageSequence; var state = graphics.Save(); FillBox(box, graphics); var imageBox = box; if (_currentFilmBox.Trim == "YES") { imageBox.Inflate(-Hundredths, -Hundredths); } if (imageSequence != null && imageSequence.Contains(DicomTag.PixelData)) { Image bitmap = null; try { var image = new DicomImage(imageSequence); var frame = image.RenderImage(); bitmap = frame; if (imgBox.Polarity == "REVERSE") { bitmap = Transform((Bitmap)bitmap); } DrawBitmap(graphics, box, bitmap, imageResolution); } finally { if (bitmap != null) { bitmap.Dispose(); } } } graphics.Restore(state); }
private void OnClickSave(object sender, EventArgs e) { var sfd = new SaveFileDialog(); sfd.Filter = "DICOM (*.dcm)|*.dcm|Image (*.bmp;*.jpg;*.png;*.gif)|*.bmp;*.jpg;*.png;*.gif"; if (sfd.ShowDialog() == DialogResult.Cancel) return; if (sfd.FilterIndex == 1) { var file = new DicomFile(_file.Dataset); file.Save(sfd.FileName); } else { var image = new DicomImage(_file.Dataset); image.RenderImage().Save(sfd.FileName); } }
public async void OpenFiles() { var files = await this.readerService.GetFilesAsync(); if (files == null || files.Count == 0) { return; } this.images = null; this.File = null; this.NumberOfImages = 0; if (files.Count == 1) { this.File = files.Single(); } var imageFiles = files.Where(f => f.Dataset.Contains(DicomTag.PixelData)).ToList(); if (imageFiles.Count > 0) { this.images = imageFiles.SelectMany( imageFile => { var dicomImage = new DicomImage(imageFile.Dataset); return Enumerable.Range(0, dicomImage.NumberOfFrames) .Select(frame => dicomImage.RenderImage(frame).As<ImageSource>()); }).ToList(); this.NumberOfImages = this.images.Count; } }
private void updateDisplay() { // Don't display if we have no filepaths yet. if (FileList == null) { return; } // Change displayed image. var newFile = FileList[currentFile]; var image = new DicomImage(newFile); this.imageDisplay.Image = image.RenderImage().AsBitmap(); // Change filename display. this.currentFileLabel.Text = Path.GetFileName(newFile); // Change metadata display var data = DicomFile.Open(newFile); this.informationBox.Clear(); new DicomDatasetWalker(data.FileMetaInfo).Walk(new DumpWalker(this)); new DicomDatasetWalker(data.Dataset).Walk(new DumpWalker(this)); }
static void Main(string[] args) { try { DicomException.OnException += delegate(object sender, DicomExceptionEventArgs ea) { ConsoleColor old = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(ea.Exception); Console.ForegroundColor = old; }; //var server = new DicomServer<DicomCEchoProvider>(12345); //var client = new DicomClient(); //client.NegotiateAsyncOps(); //for (int i = 0; i < 10; i++) // client.AddRequest(new DicomCEchoRequest()); //client.Send("127.0.0.1", 12345, false, "SCU", "ANY-SCP"); var samplesDir = Path.Combine(Path.GetPathRoot(Environment.CurrentDirectory), "Development", "fo-dicom-samples"); var testDir = Path.Combine(samplesDir, "Test"); if (!Directory.Exists(testDir)) Directory.CreateDirectory(testDir); //var img = new DicomImage(samplesDir + @"\ClearCanvas\CRStudy\1.3.51.5145.5142.20010109.1105627.1.0.1.dcm"); //img.RenderImage().Save(testDir + @"\test.jpg"); var df = DicomFile.Open(samplesDir + @"\User Submitted\overlays.dcm"); //Console.WriteLine(df.FileMetaInfo.Get<DicomTransferSyntax>(DicomTag.TransferSyntaxUID).UID.Name); //Console.WriteLine(df.Dataset.Get<PlanarConfiguration>(DicomTag.PlanarConfiguration)); var img = new DicomImage(df.Dataset); img.RenderImage().Save(testDir + @"\test.jpg"); //df = df.ChangeTransferSyntax(DicomTransferSyntax.JPEGLSLossless); //df.Save(testDir + @"\test-jls.dcm"); //df = df.ChangeTransferSyntax(DicomTransferSyntax.JPEG2000Lossless); //df.Save(testDir + @"\test-j2k.dcm"); //df = df.ChangeTransferSyntax(DicomTransferSyntax.JPEGProcess14SV1); //df.Save(testDir + @"\test-jll.dcm"); //df = df.ChangeTransferSyntax(DicomTransferSyntax.RLELossless); //df.Save(testDir + @"\test-rle.dcm"); //df = df.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian); //df.Save(testDir + @"\test-ele.dcm"); //df = df.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRBigEndian); //df.Save(testDir + @"\test-ebe.dcm"); //df = df.ChangeTransferSyntax(DicomTransferSyntax.ImplicitVRLittleEndian); //df.Save(testDir + @"\test-ile.dcm"); //Console.WriteLine("End..."); //Console.ReadLine(); //df.WriteToLog(LogManager.GetCurrentClassLogger(), LogLevel.Info); //Console.WriteLine(DicomValueMultiplicity.Parse("1")); //Console.WriteLine(DicomValueMultiplicity.Parse("3")); //Console.WriteLine(DicomValueMultiplicity.Parse("1-3")); //Console.WriteLine(DicomValueMultiplicity.Parse("1-n")); //Console.WriteLine(DicomValueMultiplicity.Parse("2-2n")); //Console.WriteLine(DicomTag.Parse("00200020")); //Console.WriteLine(DicomTag.Parse("0008,0040")); //Console.WriteLine(DicomTag.Parse("(3000,0012)")); //Console.WriteLine(DicomTag.Parse("2000,2000:TEST CREATOR")); //Console.WriteLine(DicomTag.Parse("(4000,4000:TEST_CREATOR:2)")); //Console.WriteLine(DicomMaskedTag.Parse("(30xx,xx90)")); //Console.WriteLine(DicomMaskedTag.Parse("(3000-3021,0016)")); //DicomRange<DateTime> r = new DicomRange<DateTime>(DateTime.Now.AddSeconds(-5), DateTime.Now.AddSeconds(5)); //Console.WriteLine(r.Contains(DateTime.Now)); //Console.WriteLine(r.Contains(DateTime.Today)); //Console.WriteLine(r.Contains(DateTime.Now.AddSeconds(60))); //DicomDictionary dict = new DicomDictionary(); //dict.Load(@"F:\Development\fo-dicom\DICOM\Dictionaries\dictionary.xml", DicomDictionaryFormat.XML); //string output = Dicom.Generators.DicomTagGenerator.Generate("Dicom", "DicomTag", dict); //File.WriteAllText(@"F:\Development\fo-dicom\DICOM\DicomTagGenerated.cs", output); //output = Dicom.Generators.DicomDictionaryGenerator.Generate("Dicom", "DicomDictionary", "LoadInternalDictionary", dict); //File.WriteAllText(@"F:\Development\fo-dicom\DICOM\DicomDictionaryGenerated.cs", output); //string output = Dicom.Generators.DicomUIDGenerator.Process(@"F:\Development\fo-dicom\DICOM\Dictionaries\dictionary.xml"); //File.WriteAllText(@"F:\Development\fo-dicom\DICOM\DicomUIDGenerated.cs", output); } catch (Exception e) { if (!(e is DicomException)) Console.WriteLine(e.ToString()); } }
private void UploadButtonClick(object sender, RoutedEventArgs e) { try { var dicomRepository = new DicomDataRepository(UniqueIdentifier); var dicom = new EHealthCareDataAccess.Dicom(); var image = new DicomImage(file.Dataset); dicom.DateTime = DateTime.Now; dicom.Dicom1 = ImageToByteArray(image.RenderImage()); dicom.PatientId = this.PatientId; dicom.UniqueIdentifier = this.UniqueIdentifier; dicom.Subject = txtSubject.Text.Trim(); dicom.ProviderId = E_HealthCareProviderApp.Properties.Settings.Default.ProviderId; dicomRepository.SaveDicom(dicom); } catch (Exception ex) { MessageBox.Show(ex.Message); } // Re Load List View LoadDicom(); }
private void OnClickLoadCase(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.FileName = "*.*"; // Default file name dlg.DefaultExt = ".*"; // Default file extension. Because sometimes DICOM = *.vtk, *.dcm, *.1...n, no standard. System.Windows.Forms.FolderBrowserDialog fb = new System.Windows.Forms.FolderBrowserDialog(); fb.ShowDialog(); try { BeginStoryboard((Storyboard)FindResource("rect_homeSB")); _filePath = fb.SelectedPath; DicomFile file = null; try { string[] filePaths = Directory.GetFiles(@_filePath); file = DicomFile.Open(filePaths[0]); // terminator usually 1st or last of the series dcmFile = file; _UpdateCaseInformation(file); var overviewImage = new DicomImage(filePaths[0]); _DisplayOverviewImage(overviewImage); //[fabhar - TODO] i know this is not a good pactice, but um.. //i cant think of something yet.. ThreadPool.QueueUserWorkItem(delegate(object s) { foreach (string filename in filePaths) { var image = new DicomImage(filename); Directory.Delete("C:\\_MedData\\_MedTemp", true); Directory.CreateDirectory("C:\\_MedData\\_MedTemp\\"); image.RenderImage().Save("C:\\_MedData\\_MedTemp\\"+_numOfRow+"IMG"+".jpg"); this.Dispatcher.Invoke(new WaitCallback(_DisplayImage), image); _numOfRow = _numOfRow + 1; } }); //[fabhar] reference for future implementation of _DisplayImage() MT operation. //Thread thread1 = new Thread(new ThreadStart(A)); //thread1.Start(); //thread1.Join(); } catch (DicomFileException ex) { file = ex.File; MessageBox.Show(this, "Exception while loading DICOM file: " + ex.Message, "Error loading DICOM file"); } } catch (Exception ex) { MessageBox.Show(this, "Exception while loading DICOM file: " + ex.Message, "Error loading DICOM file"); } finally { // end update here } }
private static System.Windows.Media.ImageSource _CalculateImage(DicomImage image, ref double scale, int maxW, int maxH) { if (image.Width > image.Height) { if (image.Width > maxW) scale = (double)maxW / (double)image.Width; } else { if (image.Height > maxH) scale = (double)maxH / (double)image.Height; } if (scale != 1.0) image.Scale = scale; //convert System.Drawing.Image to WPF image System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(image.RenderImage()); IntPtr hBitmap = bmp.GetHbitmap(); System.Windows.Media.ImageSource WpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); return WpfBitmap; }
public static Bitmap GenerateBitmap(DicomDataset dataset, bool burnInOverlays = true, bool anonymize = false) { var dcmImage = new DicomImage(dataset) { OverlayColor = -1 }; var bitmap = dcmImage.RenderImage(); if (burnInOverlays) { var modality = dataset.Get<String>(DicomTag.Modality); var markers = anonymize ? AnnotationText.GenerateAnnotationItems(modality, dataset, true) : AnnotationText.GenerateAnnotationItems(modality, dataset); var perentRectangle = new Rectangle(0, 0, bitmap.Width, bitmap.Height); var bmp = new Bitmap(bitmap); var gph = Graphics.FromImage(bmp); foreach (var annotationItem in markers) { var clientRectangle = AnnotationText.CalculateSubRectangle(perentRectangle, annotationItem.AnnotationRect); // Deflate the client rectangle by 4 pixels to allow some space // between neighbouring rectangles whose borders coincide. Rectangle.Inflate(clientRectangle, -4, -4); var fontSize = clientRectangle.Height - 1; //allow p's and q's, etc to extend slightly beyond the bounding rectangle. Only completely visible lines are shown. var format = new StringFormat(); format.FormatFlags = StringFormatFlags.NoClip; format.FormatFlags |= StringFormatFlags.NoWrap; AnnotationJustification(annotationItem, format); AnnotationVerticalAlignment(annotationItem, format); var style = FontStyle.Regular; if (annotationItem.Bold) { style |= FontStyle.Bold; } if (annotationItem.Italics) { style |= FontStyle.Italic; } // Font var font = CreateFont("Century Gothic", fontSize, style, GraphicsUnit.Pixel); // Drop Shadow clientRectangle.Offset(1, 1); gph.DrawString(annotationItem.AnnotationText, font, Brushes.Black, clientRectangle, format); // Foreground Colour clientRectangle.Offset(-1, -1); gph.DrawString(annotationItem.AnnotationText, font, Brushes.White, clientRectangle, format); font.Dispose(); } // Clean Up gph.Dispose(); return bmp; } return (Bitmap)bitmap; }
/// <summary> /// returns dicomFile in the content type given by finalContentType in a HttpResponseMessage. /// If content type is dicom, transfer syntax must be set to the given transferSyntax parameter. /// </summary> /// <param name="dicomFile"></param> /// <param name="finalContentType"></param> /// <param name="transferSyntax"></param> /// <returns></returns> private HttpResponseMessage ReturnImageAsHttpResponse(DicomFile dicomFile, string finalContentType, string transferSyntax) { MediaTypeHeaderValue header = null; Stream streamContent = null; if (finalContentType == JpegImageContentType) { DicomImage image = new DicomImage(dicomFile.Dataset); Bitmap bmp = image.RenderImage(0).As<Bitmap>(); //When an image/jpeg MIME type is returned, the image shall be encoded using the JPEG baseline lossy 8 //bit Huffman encoded non-hierarchical non-sequential process ISO/IEC 10918. //TODO Is it the case with default Jpeg format from Bitmap? header = new MediaTypeHeaderValue(JpegImageContentType); streamContent = new MemoryStream(); bmp.Save(streamContent, ImageFormat.Jpeg); streamContent.Seek(0, SeekOrigin.Begin); } else if (finalContentType == AppDicomContentType) { //By default, the transfer syntax shall be //"Explicit VR Little Endian". //Note: This implies that retrieved images are sent un-compressed by default. DicomTransferSyntax requestedTransferSyntax = DicomTransferSyntax.ExplicitVRLittleEndian; if (transferSyntax != null) requestedTransferSyntax = GetTransferSyntaxFromString(transferSyntax); bool transferSyntaxIsTheSameAsSourceFile = dicomFile.FileMetaInfo.TransferSyntax == requestedTransferSyntax; //we only change transfer syntax if we need to DicomFile dicomFileToStream; if (!transferSyntaxIsTheSameAsSourceFile) { dicomFileToStream = dicomFile.ChangeTransferSyntax(requestedTransferSyntax); } else { dicomFileToStream = dicomFile; } header = new MediaTypeHeaderValue(AppDicomContentType); streamContent = new MemoryStream(); dicomFileToStream.Save(streamContent); streamContent.Seek(0, SeekOrigin.Begin); } HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(streamContent); result.Content.Headers.ContentType = header; return result; }