Convert Text to Image using C#

The article below explains how to convert text to image using C#. Here we use graphics and drawing tools to convert the string entered in textbox to image.

C# Code to convert text to image

protected void btnConvert_Click(object sender, EventArgs e)
           string text = txtText.Text.Trim();
           Bitmap bitmap = new Bitmap(1, 1);
           Font font = new Font("Calibri", 12, FontStyle.Regular, GraphicsUnit.Pixel);
           Graphics graphics = Graphics.FromImage(bitmap);
           int width = (int)graphics.MeasureString(text, font).Width;
           int height = (int)graphics.MeasureString(text, font).Height;
           bitmap = new Bitmap(bitmap, new Size(width, height));
           graphics = Graphics.FromImage(bitmap);
           graphics.SmoothingMode = SmoothingMode.AntiAlias;
           graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
           graphics.DrawString(text, font, new SolidBrush(Color.FromArgb(255, 0, 0)), 0, 0);
           string fileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".jpg";
           bitmap.Save(Server.MapPath("~/Images/") + fileName, ImageFormat.Jpeg);
           imgText.ImageUrl = "~/Images/" + fileName;
           imgText.Visible = true;


Aspx Code

<html xmlns="">
<head runat="server">
    <title>Convert Text String to Image using C#</title>
    <form id="form1" runat="server">
            <h3>Convert Text String to Image using C#</h3>

            Enter text to convert
            <asp:TextBox runat="server" ID="txtText"></asp:TextBox>
            <br />
            <asp:Button ID="btnConvert" runat="server" Text="Convert" OnClick="btnConvert_Click" />
            <hr />
            <asp:Image ID="imgText" runat="server" Visible="false" />



The output below shows how the text entered in the textbox control is converted to image as shown after the separator line.


Demo Code

Download Demo