Sometimes we need to convert text into the images on the fly. This code converts the text into image and displays it onto the web page without saving it into a file on the disk. It also takes care of text wrapping.
TextToImageConvertor can either be used in a web page or in a module. I have used this code in a web page. To use TextToImageConvertor in a module, you will need to make some changes in the step 8.
The code for TextToImageConvertor is self explanatory. However, I am going to describe this step-by-step.
Step 0 - Include Namespaces
using System.Drawing;
using System.Drawing.Imaging;
Step 1 - Declare Properties
Declare some variables that will control the behavior and color of the image.
string Text = Request.QueryString["Text"];
Color FontColor = Color.Blue;
Color BackColor = Color.White;
String FontName = "Times New Roman";
int FontSize = 10;
int Height = 150;
int Width = 150;
Step 2 - Create a Bitmap Object to Hold The Image
Bitmap bitmap = new Bitmap(Width, Height);
Step 3 - Create a Graphics object using this Bitmap object
Graphics graphics = Graphics.FromImage(bitmap);
Step 4 - Create Color, Font, and PointF objects.
Color color = Color.Gray; ;
Font font = new Font(FontName, FontSize);
//define where the text will be displayed in the specified area of the image
PointF point = new PointF(5.0F, 5.0F);
Step 5 - Create Brushes and Pen
SolidBrush BrushForeColor = new SolidBrush(FontColor);
SolidBrush BrushBackColor = new SolidBrush(BackColor);
Pen BorderPen = new Pen(color);
Step 6 - Draw Rectangle using Graphics object
Rectangle displayRectangle = new Rectangle(new Point(0, 0), new Size(Width - 1, Height - 1));
graphics.FillRectangle(BrushBackColor, displayRectangle);
graphics.DrawRectangle(BorderPen, displayRectangle);
Step 7 - Draw Text string on the specified rectangle using Graphics object
//Define string format
StringFormat format1 = new StringFormat(StringFormatFlags.NoClip);
StringFormat format2 = new StringFormat(format1);
//Draw text string using the text format
graphics.DrawString(Text, font, Brushes.Red, (RectangleF)displayRectangle, format2);
Step 8 - Send the bitmap to page output stream in JPEG format
Response.ContentType = "image/jpeg";
bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
Using TextToImageConvertor
TextToImageConvertor is developed as a web page which can be accessed directly by passing the text in he query string.
To demonstrate the use of this tool, create a webpage with a textbox, a button and an image control. On the click event of the button, set the image URL to the convertor page and pass the text of text box into the query string. In the example code below, I have named my image control as img1 and text box as txtNote.
img1.ImageUrl = "default2.aspx?Text=" + txtNote.Text;
Technorati Tags:
ASP.net,
Graphics