How to add text to a bitmap image programmatically? WPF

前端 未结 2 540
有刺的猬
有刺的猬 2021-01-02 14:21

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

2条回答
  •  迷失自我
    2021-01-02 15:03

    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.

提交回复
热议问题