public void Initialise(DicomFile dcmFile, String filePath) { _filePath = filePath; DicomFile file = null; file = dcmFile; _UpdateInfo(file); try { string[] filePaths = Directory.GetFiles(@_filePath); ThreadPool.QueueUserWorkItem(delegate(object s) { foreach (string filename in filePaths) { var image = new DicomImage(filename); this.Dispatcher.BeginInvoke(new WaitCallback(_DisplayImage), image); _numOfRow = _numOfRow + 1; } }); } catch (DicomFileException ex) { file = ex.File; MessageBox.Show(this, "Exception while loading DICOM file: " + ex.Message, "Error loading DICOM file"); } }
public void RenderImage_WPFManager_AsReturnsImageSource() { lock (this.@lock) { ImageManager.SetImplementation(WPFImageManager.Instance); var image = new DicomImage(@".\Test Data\CT-MONO2-16-ankle").RenderImage(); Assert.IsAssignableFrom<ImageSource>(image.As<ImageSource>()); } }
private async void MainPageOnLoaded(object sender, RoutedEventArgs e) { var downloadButton = ApplicationBar.Buttons.OfType<ApplicationBarIconButton>().SingleOrDefault(btn => btn.Text.Equals("DownloadButton")); if (downloadButton != null) downloadButton.Text = AppResources.AppBarDownloadButtonText; var settingsButton = ApplicationBar.Buttons.OfType<ApplicationBarIconButton>().SingleOrDefault(btn => btn.Text.Equals("SettingsButton")); if (settingsButton != null) settingsButton.Text = AppResources.AppBarSettingsButtonText; var uri = new Uri("ms-appx:///Images/CT-MONO2-16-ankle.dcm"); var file = await StorageFile.GetFileFromApplicationUriAsync(uri); var stream = (await file.OpenAsync(FileAccessMode.Read)).AsStream(); var dicomObj = DicomFile.Open(stream); _textItems.Clear(); new DicomDatasetWalker(dicomObj.FileMetaInfo).Walk(new DicomDumpWalker(_textItems)); new DicomDatasetWalker(dicomObj.Dataset).Walk(new DicomDumpWalker(_textItems)); var dicomImage = new DicomImage(dicomObj.Dataset); DicomImageSource = dicomImage.RenderImageSource(); }
protected override void OnLoad(EventArgs e) { // execute on ThreadPool to avoid STA WaitHandle.WaitAll exception ThreadPool.QueueUserWorkItem( delegate(object s) { try { _image = new DicomImage(_file.Dataset); _grayscale = !_image.PhotometricInterpretation.IsColor; if (_grayscale) { _windowWidth = _image.WindowWidth; _windowCenter = _image.WindowCenter; } _frame = 0; Invoke(new WaitCallback(SizeForImage), _image); Invoke(new WaitCallback(DisplayImage), _image); } catch (Exception ex) { OnException(ex); } }); }
/// <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); }
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 RenderImage_WinFormsManager_AsReturnsBitmap() { lock (this.@lock) { ImageManager.SetImplementation(WinFormsImageManager.Instance); var image = new DicomImage(@".\Test Data\CT-MONO2-16-ankle").RenderImage(); Assert.IsAssignableFrom<Bitmap>(image.As<Bitmap>()); } }
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); } }
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 void UploadDicomFile(string guid) { string dirPath = string.Format(@"C:\temp\{0}", guid); string filePath = string.Format(@"{0}\{1}", dirPath, new DirectoryInfo(dirPath).GetFiles().Single().Name); try { using (TransactionScope scope = new TransactionScope()) { DicomDataset dataset = Dicom.DicomFile.Open(filePath).Dataset; // Vlozenie dat do DicomFile FileInfo fileInfo = new FileInfo(filePath); DateTime uploadTime = DateTime.Now; int studyId = int.Parse(dataset.Get<string>(DicomTag.StudyID)); string name = fileInfo.Name; DicomFile dicomFileEntity = new DicomFile { UploadTime = uploadTime, StudyId = studyId, Name = name }; ObjectContext.DicomFile.AddObject(dicomFileEntity); ObjectContext.SaveChanges(); int fileId = (from df in ObjectContext.DicomFile select df.FileId).DefaultIfEmpty().Max(); // Vlozenie dat do DicomElement a DicomElementValue foreach (DicomItem element in dataset) { int groupNumber = element.Tag.Group; int elementNumber = element.Tag.Element; string valueRepresentation = element.ValueRepresentation.ToString(); string valueMultiplicity = element.Tag.DictionaryEntry.ValueMultiplicity.ToString(); string keyword = element.Tag.DictionaryEntry.Keyword; bool elementExists = Convert.ToBoolean(( from de in ObjectContext.DicomElement where de.GroupNumber == groupNumber && de.ElementNumber == elementNumber select de).Count()); if (!elementExists) { DicomElement dicomElementEntity = new DicomElement { GroupNumber = groupNumber, ElementNumber = elementNumber, ValueRepresentation = valueRepresentation, ValueMultiplicity = valueMultiplicity, Keyword = keyword }; ObjectContext.DicomElement.AddObject(dicomElementEntity); ObjectContext.SaveChanges(); } string value = dataset.Get<string>(element.Tag); DicomElementValue dicomElementValueEntity = new DicomElementValue { Value = value, FileId = fileId, GroupNumber = groupNumber, ElementNumber = elementNumber }; ObjectContext.DicomElementValue.AddObject(dicomElementValueEntity); ObjectContext.SaveChanges(); } //Vlozenie dat do DicomFrame DicomImage dicomImage = new DicomImage(filePath); for (int i = 0; i < dicomImage.NumberOfFrames; i++) { Guid frameGuid = Guid.NewGuid(); byte[] frame = dicomImage.PixelData.GetFrame(i).Data;// RangeByteBuffer DicomFrame dicomFrameEntity = new DicomFrame { FileId = fileId, FrameGuid = frameGuid, Frame = frame }; ObjectContext.DicomFrame.AddObject(dicomFrameEntity); ObjectContext.SaveChanges(); } scope.Complete(); } } finally { if (File.Exists(filePath)) File.Delete(filePath); if (Directory.Exists(dirPath)) Directory.Delete(dirPath); } }
/// <summary> /// Convert the byte data retrieved from DCM file to Image /// </summary> /// <param name="imagedata"></param> /// <returns></returns> private Bitmap ConvertDCMData2BitImage(DicomFile dcm) { DicomFile newDcmFile = null; if (dcm.FileMetaInfo.TransferSyntax.IsEncapsulated)//if the data is compressed { // System.Reflection.Assembly.LoadFrom(Path.Combine(Application.StartupPath,"Dicom.Native64.dll")); DicomTranscoder.LoadCodecs(Application.StartupPath, "Dicom.Native*.dll"); newDcmFile=dcm.ChangeTransferSyntax(DicomTransferSyntax.ExplicitVRLittleEndian,new DicomJpegLsParams()); } DicomImage imageDcm=null; if (newDcmFile != null) imageDcm = new DicomImage(newDcmFile.Dataset); else imageDcm = new DicomImage(dcm.Dataset); DicomDataset dataset = dcm.Dataset; byte[] fs = imageDcm.PixelData.NumberOfFrames < 2 ? imageDcm.PixelData.GetFrame(0).Data : imageDcm.PixelData.GetFrame(1).Data; uint size = (uint)Marshal.SizeOf(typeof(short)); uint padding = (uint)fs.Length % size; uint count = (uint)fs.Length / size; short[] values = new short[count]; System.Buffer.BlockCopy(fs, 0, values, 0, (int)(fs.Length - padding)); int height = dataset.Get<int>(DicomTag.Rows); int width = dataset.Get<int>(DicomTag.Columns); int windowsWidth = (int)dataset.Get<double>(DicomTag.WindowWidth); int windowsCenter = (int)dataset.Get<double>(DicomTag.WindowCenter); //if the windowsWidth = 0, the DCM file is not standard type. if (windowsWidth == 0 || windowsCenter==0) { windowsWidth = values.Max<short>()-values.Min<short>(); windowsCenter = windowsWidth / 2; } int low = windowsCenter - windowsWidth / 2; int high = windowsCenter + windowsWidth / 2; Bitmap bitmap = new Bitmap(width, height); for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { int r, g, b; int temp = (int)values[(width - j - 1) * height + i]; int val = temp > high ? 255 : (temp < low ? 0 : ((temp - low) * 255 / windowsWidth)); r = g = b = val; bitmap.SetPixel(i, width-j-1, Color.FromArgb(r, g, b)); } } return bitmap; }
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; }
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 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); } }
void StoreImage(DicomDataset ds, string modality) { DicomImage di = new DicomImage(ds); // store in cached resource var idc = new ImageDataContract(); idc.PatientId = ds.Get<string>(DicomTag.PatientID); if (ds.Contains(DicomTag.PixelSpacing)) { idc.PixelSpacing = new VoxelSize() { X = Convert.ToSingle(ds.Get<double>(DicomTag.PixelSpacing, 0)), Y = Convert.ToSingle(ds.Get<double>(DicomTag.PixelSpacing, 1)), }; } else { idc.PixelSpacing = new VoxelSize() { X = 1.0f, Y = 1.0f, }; } idc.ImagePosition = new ImagePosition() { X = Convert.ToSingle(ds.Get<double>(DicomTag.ImagePositionPatient, 0)), Y = Convert.ToSingle(ds.Get<double>(DicomTag.ImagePositionPatient, 1)), Z = Convert.ToSingle(ds.Get<double>(DicomTag.ImagePositionPatient, 2)), }; idc.ImageOrientation = new ImageOrientation(); idc.ImageOrientation.Row = new DirectionCosine() { X = Convert.ToSingle(ds.Get<double>(DicomTag.ImageOrientationPatient, 0)), Y = Convert.ToSingle(ds.Get<double>(DicomTag.ImageOrientationPatient, 1)), Z = Convert.ToSingle(ds.Get<double>(DicomTag.ImageOrientationPatient, 2)), }; idc.ImageOrientation.Column = new DirectionCosine() { X = Convert.ToSingle(ds.Get<double>(DicomTag.ImageOrientationPatient, 3)), Y = Convert.ToSingle(ds.Get<double>(DicomTag.ImageOrientationPatient, 4)), Z = Convert.ToSingle(ds.Get<double>(DicomTag.ImageOrientationPatient, 5)), }; idc.Width = di.Width; idc.Height = di.Height; idc.Label = string.Format("{0} {1}", modality, ds.GetDateTime(DicomTag.SeriesDate, DicomTag.SeriesTime).ToString()); idc.SeriesInstanceUID = ds.Get<string>(DicomTag.SeriesInstanceUID); // store for association closed event _seriesInstanceUIDs.Add(idc.SeriesInstanceUID); string for_uid = ds.Get<string>(DicomTag.FrameOfReferenceUID); idc.FrameOfReferenceUID = for_uid; LocalImageResourceManagerClient cache1 = new LocalImageResourceManagerClient(); idc = cache1.AddImage(idc); double repoGb = cache1.GetRepositorySizeGB(); cache1.Close(); if (di.PhotometricInterpretation == PhotometricInterpretation.Monochrome1 || di.PhotometricInterpretation == PhotometricInterpretation.Monochrome2) { var dsForWl = di.Dataset; if (_firstImageIn.ContainsKey(idc.SeriesInstanceUID)) { dsForWl = _firstImageIn[idc.SeriesInstanceUID].Dataset; } else { _firstImageIn.TryAdd(idc.SeriesInstanceUID, di); } var gro = GrayscaleRenderOptions.FromDataset(dsForWl); var voilut = VOILUT.Create(gro); var ipd = PixelDataFactory.Create(di.PixelData, 0); int[] outPixelsInt = new int[di.Width * di.Height]; ipd.Render(voilut, outPixelsInt); ushort[] outPixelsUshort = Array.ConvertAll(outPixelsInt, new Converter<int, ushort>(inInt => (ushort)(inInt))); var handle = idc.PixelBuffer.GetHandle(); handle.WriteArray<ushort>(0, outPixelsUshort, 0, outPixelsUshort.Length); idc.PixelBuffer.ReleaseHandle(); idc.PixelBuffer.CloseMapping(); // inform of found image ImageResponseClient proxy = ImageResponseClient.CreateProxy(); proxy.OnImageStored(idc.ImageId, repoGb); proxy.Close(); } }
/// <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; }
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 } }
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); }