using System;
using System.Collections;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Dicom;
using Dicom.IO;
using Dicom.IO.Buffer;
namespace OverlayFromTextBlock
{
class Program
{
[STAThread]
static void Main(string[] args)
{
try
{
DicomFile df = DicomFile.Open("smpte.dcm");
ushort width = df.Dataset.Get<ushort>(DicomTag.Columns);
ushort height = df.Dataset.Get<ushort>(DicomTag.Rows);
var grid = new Grid { Width = width, Height = height };
var text = new TextBlock
{
Text = "OVERLAY",
FontSize = 32,
FontWeight = FontWeights.Bold,
HorizontalAlignment = HorizontalAlignment.Center
};
grid.Children.Add(text);
grid.Measure(new Size(grid.Width, grid.Height));
grid.Arrange(new Rect(new Size(grid.Width, grid.Height)));
var rtb = new RenderTargetBitmap(
(int)grid.Width,
(int)grid.Height,
96,
96,
PixelFormats.Pbgra32);
rtb.Render(grid);
int stride = rtb.PixelWidth * 4;
int size = rtb.PixelHeight * stride;
byte[] coloredPixels = new byte[size];
rtb.CopyPixels(coloredPixels, stride, 0);
byte[] pixels = new byte[size/4];
df.Dataset.Add(new DicomUnsignedShort(new DicomTag(0x6000,0x0010), width));
df.Dataset.Add(new DicomUnsignedShort(new DicomTag(0x6000,0x0011), height));
df.Dataset.Add(new DicomCodeString(new DicomTag(0x6000,0x0040), "G"));
df.Dataset.Add(new DicomSignedShort(new DicomTag(0x6000,0x0050), new short[] {1, 1}));
df.Dataset.Add(new DicomUnsignedShort(new DicomTag(0x6000,0x0100), 1));
df.Dataset.Add(new DicomUnsignedShort(new DicomTag(0x6000,0x0102), 0));
BitArray bits = new BitArray(width * height);
for (int i = 0; i < size/4; i++)
{
bits[i] = coloredPixels[4*i+3]==0 ? false : true;
}
byte[] packedbitarray = new byte[Math.Max(1, bits.Length / 8)];
bits.CopyTo(packedbitarray, 0);
MemoryByteBuffer buffer = new MemoryByteBuffer(packedbitarray);
df.Dataset.Add(new DicomOtherByte(new DicomTag(0x6000,0x3000), buffer));
DicomFile dfnew = new DicomFile(df.Dataset);
dfnew.Save("overlay.dcm");
}
catch (Exception e) { Console.WriteLine(e.Message); }
}
}
}