How to add text to a bitmap image programmatically? WPF

17,588

Solution 1

You can achieve this using DrawingVisual and DrawingImage classes :

enter image description here

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.

Solution 2

You don't need to draw the text into the image itself. In your XAML just add a TextBlock control at a higher Z order.

Share:
17,588
Brian Var
Author by

Brian Var

I'm a creative web developer with 5+ years’ experience in front-end development and a keen interest in developing responsive dashboards. I've constructed contact center, administration and reporting web applications using the latest JavaScript frameworks. I have good experience in performing requirements scoping.

Updated on June 19, 2022

Comments

  • Brian Var
    Brian Var almost 2 years

    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);
    
                }
            } 
    

    Kinect video feed with overlay text