Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add text to a bitmap image programmatically? WPF

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

like image 267
Brian Var Avatar asked Feb 19 '14 19:02

Brian Var


2 Answers

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.

like image 61
aybe Avatar answered Sep 16 '22 19:09

aybe


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.

like image 40
NickC Avatar answered Sep 19 '22 19:09

NickC