How to add text to a bitmap image programmatically? WPF

bitmap, c#, drawing, wpf

Solution

You can achieve this using `DrawingVisual` and `DrawingImage` classes :

var random = new Random();
var pixels = new byte[256 * 256 * 4];
random.NextBytes(pixels);
BitmapSource bitmapSource = BitmapSource.Create(256, 256, 96, 96, PixelFormats.Pbgra32, null, pixels, 256 * 4);
var visual = new DrawingVisual();
using (DrawingContext drawingContext = visual.RenderOpen())
{
    drawingContext.DrawImage(bitmapSource, new Rect(0, 0, 256, 256));
    drawingContext.DrawText(
        new FormattedText("Hi!", CultureInfo.InvariantCulture, FlowDirection.LeftToRight,
            new Typeface("Segoe UI"), 32, Brushes.Black), new Point(0, 0));
}
var image = new DrawingImage(visual.Drawing);
Image1.Source = image;

Unfortunately you will have to create a new `BitmapSource` as there's currently no way I know of writing text directly to it.

Alternatively you could use `WriteableBitmapEx` : https://writeablebitmapex.codeplex.com/

- create a WriteableBitmap from your frame using `BitmapFactory` (1)

- create another WriteableBitmap and draw text on it using the above method (2)

- blit the text bitmap (2) over your frame (1)

Same result but different approach, not sure whether approach 2 is better as it's cumbersome.

Problem

I'm using a Kinect sensor to show a video feed on an image by setting the video feed as bitmap source like shown below. But my question is how would I add text to the image/bitmap for example a score counter, I added a picture below to show what I'm trying to achieve. ``` void myKinect_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e) { using (ColorImageFrame colorFrame = e.OpenColorImageFrame()) { if (colorFrame == null) return; byte[] colorData = new byte[colorFrame.PixelDataLength]; colorFrame.CopyPixelDataTo(colorData); KinectVideo.Source = BitmapSource.Create(colorFrame.Width, colorFrame.Height, 96, 96, PixelFormats.Bgr32, null, colorData, colorFrame.Width * colorFrame.BytesPerPixel); } } ```

Original source

Related problems