Kuczi
Kuczi

Reputation: 387

Creating an image with text and saving it as .png in C# using WPF

We are working on an Optical Character Recognition system and i want to compare how different renderers render text. I want to make a simple program that creates an image, writes some text on it with different fonts, sizes and styles and saves it to a .png file(I want to have all sizes, fonts styles i need in one file so they are easy to compare). I've managed to do it with GDI and GDI+ renderers using Bitmap. Now i'm trying to do the same thing in a WPF application, as I've heard rendering text there is different. Is it possible to use BitmapImage for that? Coming from Windows Forms I presume this problem should be pretty simple but i just can't seem to do it in WPF.

This is a simplified version of how i did it with GDI+ Renderer:

public void CreateAndSave()
{
    Bitmap bitmap = new Bitmap(500, 500, PixelFormat.Format24bppRgb);
    Graphics g = Graphics.FromImage(bitmap);
    g.Clear(Color.White);
    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
    g.DrawString("sample text", font, brush, x, y);
    bitmap.Save(fileName);
}

Is there any similar way of doing this with WPF?

Upvotes: 4

Views: 2797

Answers (2)

Ugur
Ugur

Reputation: 1256

Such as methods like "DrawString" are costly in WPF. Instead of that doing that, you can create a canvas/grid and put the text box or labels etc. and then you can render that canvas/grid. You can use that code:

public void ConvertToBitmapSource(UIElement element)
{
    var target = new RenderTargetBitmap(
        (int)element.RenderSize.Width, (int)element.RenderSize.Height,
        96, 96, PixelFormats.Pbgra32);
    target.Render(element);

    var encoder = new PngBitmapEncoder();
    var outputFrame = BitmapFrame.Create(target);
    encoder.Frames.Add(outputFrame);

    using (var file = File.OpenWrite("TestImage.png"))
    {
        encoder.Save(file);
    }
}

Upvotes: 3

OrMiz
OrMiz

Reputation: 275

Use the FormattedText class to build a Geometry object, take an example from here: https://msdn.microsoft.com/en-us/library/system.windows.media.formattedtext.buildgeometry(v=vs.110).aspx

Then, use one of the BitmapEncoder classes to save the Geometry object you've built. Look at that example: https://stackoverflow.com/a/9081295/3730455

Upvotes: 0

Related Questions