Reputation: 31
How do I convert text into an image? The image resolution has to be really small ~30x30 to 100x100 and should only be a single color.
I've tried using GDI to do it but it generates text with multiple colors because of aliasing and whatnot.
Upvotes: 2
Views: 3995
Reputation: 220
Try this. You can use the GraphicsObject in the code below to set the default type for text rendering which is no antialiasing. You can set the color using any combination of RGB that you want (single or multiple). I have used color brown here
private Bitmap CreateImageFromText(string Text)
{
// Create the Font object for the image text drawing.
Font textFont = new Font("Arial", 25, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
Bitmap ImageObject = new Bitmap(30, 30);
// Add the anti aliasing or color settings.
Graphics GraphicsObject = Graphics.FromImage(ImageObject);
// Set Background color
GraphicsObject.Clear(Color.White);
// to specify no aliasing
GraphicsObject.SmoothingMode = SmoothingMode.Default;
GraphicsObject.TextRenderingHint = TextRenderingHint.SystemDefault;
GraphicsObject.DrawString(Text, textFont, new SolidBrush(Color.Brown), 0, 0);
GraphicsObject.Flush();
return (ImageObject);
}
You can call this function with the string you like and than use Bitmap.Save method to save your image. Please note you will need to use namespaces System.Drawing, System.Drawing.Drawing2D, System.Drawing.Text
Upvotes: 0
Reputation: 760
For an image, render the textblock to a bitmap using the RenderTargetBitmap.Render() as described here. Here is an example where you render a TextBlock "textblock", and assign the result to an Image "image"
var bitmap = new RenderTargetBitmap();
bitmap.Render(textblock);
image.Source = bitmap;
Upvotes: 3