We can easily convert text to image in C# by using
System.Drawing
namespace. Here these tips will guide you how to create bitmap image from text. It’s using
Graphics
property of
System.Drawing
namespace to convert text to bitmap image and place the image in a picture box. The
Graphics
class provides methods for drawing to the display device.
In this article, you will see a method
Convert_Text_to_Image(string txt, string fontname, int fontsize)
is responsible to return Bitmap Image on the basis of
Text,
fontname and
fontsize.
Take a look at how to use the mentioned method for converting Text to Image:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Text_to_Image
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static Bitmap Convert_Text_to_Image(string txt, string fontname, int fontsize)
{
Bitmap bmp = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(bmp);
Font font = new Font(fontname, fontsize);
SizeF stringSize = graphics.MeasureString(txt, font);
bmp = new Bitmap(bmp,(int)stringSize.Width,(int)stringSize.Height);
graphics = Graphics.FromImage(bmp);
graphics.DrawString(txt, font, Brushes.Red, 0, 0);
font.Dispose();
graphics.Flush();
graphics.Dispose();
return bmp;
}
private void btnconvert_Click(object sender, EventArgs e)
{
picbox.Image = Convert_Text_to_Image(txtvalue.Text, "Bookman Old Style", 20);
picbox.SizeMode = PictureBoxSizeMode.StretchImage;
}
}
}
Now write something in
Textbox
and then press convert button to see the desired output.
Go
there[
^] to download source code.
[Edited] Another approach
public Bitmap ConvertTextToImage(string txt, string fontname, int fontsize, Color bgcolor, Color fcolor, int width, int Height)
{
Bitmap bmp = new Bitmap(width, Height);
using (Graphics graphics = Graphics.FromImage(bmp))
{
Font font = new Font(fontname, fontsize);
graphics.FillRectangle(new SolidBrush(bgcolor), 0, 0, bmp.Width, bmp.Height);
graphics.DrawString(txt, font, new SolidBrush(fcolor), 0, 0);
graphics.Flush();
font.Dispose();
graphics.Dispose();
}
return bmp;
}
Take a look how to use Method in same Project.
private void btnconvert_Click(object sender, EventArgs e)
{
picbox.Image = this.ConvertTextToImage(txtvalue.Text, "Bookman Old Style", 10, Color.Yellow, Color.Red, txtvalue.Width, txtvalue.Height);
}
Go
there[
^] to Download Edited Source Code.