Convert text to image in ASP.NET

In this blog we will learn how to convert text to an Image.


I have an ASP.NET page that has a TextBox control. When user enters any text to the TextBox and clicks the button, then the text is converted to an image.

 

Note: - Here we need two namespaces.

using System.Drawing;

using System.Drawing.Imaging;

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Untitled Page</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

     <asp:TextBox ID="TextBox1" runat="server" Width="200px"></asp:TextBox>

        <br /><br />

       

        <asp:Button ID="btnconvert" runat="server" Text="Convert to image"

            onclick="btnconvert_Click" />

    </div>

    </form>

</body>

</html>

 

 

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

using System.IO;

using System.Drawing;

using System.Drawing.Imaging;

public partial class _Default : System.Web.UI.Page

{

    protected void btnconvert_Click(object sender, EventArgs e)

    {

        Bitmap bit1 = new Bitmap(200, 30, System.Drawing.Imaging.PixelFormat.Format64bppArgb);

        Graphics gph1 = Graphics.FromImage(bit1);

        string text;

        gph1.Clear(Color.Orange);

        text = TextBox1.Text;

        gph1.DrawString(text, new Font("Arial", 12, FontStyle.Bold),

        new SolidBrush(Color.Red), new PointF(0.4F, 2.4F));

        Response.ContentType = "image/Jpeg";

        bit1.Save(Response.OutputStream, ImageFormat.Jpeg);

        bit1.Dispose();

    }

}

 

 

 

 

Next Recommended Reading Reduce image size/ Generate thumbnails