Asp.net Convert String To Image

Asp.net Convert String To Image Asp.net Convert String To Image.

In Asp.net, you can convert the given text string to image. In this post we will see how to convert the input string into image and display on webpage. we will use Asp.net with C#.net and VB.net to show converted string to image.

You can use this technique to generate captcha image challenges as explained in below post.

URL: Asp.net captcha text generator. It’s very simple to understand and use it. Your web application has to auto generate a text and store it in Session variable. The text stored inside session variable is converted into image known as CAPTCHA image. When user tries to submit the data, ask them to submit the content written in image. Validate the user submitted content against text stored in session. If session text and user submitted data get matched, process other data submitted by user to enter in database. This indicates that the user is human, as it’s hard for software program read image content and post it.

First look at the function which accepts string as a parameter to convert into an Image. We will use below namespaces. To use those namespaces, you may require to add reference of System.Drawing.

using System.Drawing;
using System.Drawing.Imaging;

Here is a function which actually converts given string into an Image. You can reuse this function in your windows application also.

C# String To Image.

  
 Bitmap ConvertStringToImage(string inputString)
  {

    Bitmap b = new Bitmap(250, 50);

    Font f = new Font("Arial", 15F);

    Graphics g = Graphics.FromImage(b);

    SolidBrush whiteBrush = new SolidBrush(Color.BlueViolet);
    SolidBrush blackBrush = new SolidBrush(Color.Red);

    RectangleF canvas = new RectangleF(0, 0, 250, 50);

    g.FillRectangle(whiteBrush, canvas);
    g.DrawString(inputString, f, blackBrush, canvas);

    return b;

  }

Save method of bitmap instance can write image output to response stream. Stream can be file or output stream of Response in Asp.net.

Description

An Instance of Bitmap b is passed to constructor of Graphic object. Graphics object is then used to Fill the image height, width, font of string and other parameters. Finally, ConvertStringToImage function returns bitmap instance.

Here is complete code behind file of Asp.net and aspx web page.

<form id="form1" runat="server">
   <div>
       Enter Text:
       <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>&nbsp;<asp:Button ID="Button1"
           runat="server" OnClick="Button1_Click" Text="Convert To Image" />
       <br />
       <asp:Image ID="Image1" runat="server" ImageUrl="StringToImage.aspx" />Enter Text:
       &nbsp;
       <br />
       </div>
   </form>

Code behind file of convert string to image in Asp.net

using System;
using System.Web;

using System.Drawing;
using System.Drawing.Imaging;



public partial class StringToImage : System.Web.UI.Page
{

  protected void Button1_Click(object sender, EventArgs e)
  {

    Response.Clear();
    Response.ContentType = "image/gif";

    Bitmap b = ConvertStringToImage(TextBox1.Text);
    b.Save(Context.Response.OutputStream, ImageFormat.Gif);

    Response.End();

  }


  Bitmap ConvertStringToImage(string inputString)
  {

    Bitmap b = new Bitmap(250, 50);

    Font f = new Font("Arial", 15F);

    Graphics g = Graphics.FromImage(b);

    SolidBrush whiteBrush = new SolidBrush(Color.BlueViolet);
    SolidBrush blackBrush = new SolidBrush(Color.Red);

    RectangleF canvas = new RectangleF(0, 0, 250, 50);

    g.FillRectangle(whiteBrush, canvas);
    g.DrawString(inputString, f, blackBrush, canvas);

    return b;

  }
  protected void Page_Load(object sender, EventArgs e)
  {

  }
}

Convert Text to Image console application.

Here is a console application which converts given string into image and store it at specified location.

using System;
using System.IO;

using System.Drawing;
using System.Drawing.Imaging;


namespace Csharp.StringToImage.Example
{
  class Program
  {
    static void Main(string[] args)
    {

      FileStream imagefileStream = new FileStream(@"C:\satalaj.gif",FileMode.OpenOrCreate);
      
      string inputString = "www.satalaj.com";

      Bitmap b = ConvertStringToImage(inputString);
      
      b.Save(imagefileStream,ImageFormat.Gif);
      
      Console.WriteLine("String has been converted into an image.");
      Console.ReadLine();
    }

    private static Bitmap ConvertStringToImage(string inputString)
    {
      Bitmap b = new Bitmap(250, 50);

      Font f = new Font("Arial", 15F);

      Graphics g = Graphics.FromImage(b);

      SolidBrush whiteBrush = new SolidBrush(Color.BlueViolet);
      SolidBrush blackBrush = new SolidBrush(Color.Red);

      RectangleF canvas = new RectangleF(0, 0, 250, 50);

      g.FillRectangle(whiteBrush, canvas);
      g.DrawString(inputString, f, blackBrush, canvas);

      return b;
    }

    
  }
}

VB.net String to Image example.

Below is VB.net string to Image conversion example. It uses same function which we have already discussed.

VB.net convert string to Image
Imports System
Imports System.IO

Imports System.Drawing
Imports System.Drawing.Imaging


Namespace Csharp.StringToImage.Example
	Class Program
		Private Shared Sub Main(args As String())

		Dim imagefileStream As New FileStream("C:\satalaj.gif", FileMode.OpenOrCreate)

		Dim inputString As String = "www.satalaj.com"

		Dim b As Bitmap = ConvertStringToImage(inputString)

		b.Save(imagefileStream, ImageFormat.Gif)

		Console.WriteLine("String has been converted into an image.")
		Console.ReadLine()
		End Sub

		Private Shared Function ConvertStringToImage(inputString As String) As Bitmap

		Dim b As New Bitmap(250, 50)

		Dim f As New Font("Arial", 15F)

		Dim g As Graphics = Graphics.FromImage(b)

		Dim whiteBrush As New SolidBrush(Color.BlueViolet)

		Dim blackBrush As New SolidBrush(Color.Red)
			Dim canvas As New RectangleF(0, 0, 250, 50)

			g.FillRectangle(whiteBrush, canvas)
			g.DrawString(inputString, f, blackBrush, canvas)

			Return b
		End Function


	End Class
End Namespace

Description The console application uses the same function to generate image from text string.

We are creating file stream instance to locate the generated image. By calling save method with file stream parameter we are actually saving the generated image output to actual image. You can also compress an image before storing or rendering to browser.

Summery You can convert text to image using System.Drawing assembly reference and C#.net or VB.net program. It is very helpful in Captcha image generation.

You can generate random text to image. Try to change the font and other parameters to generate other effects.

You can also convert byte array of image into Base64 string and embed the image in web page.

Tags:

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.