Click here to Skip to main content
Licence 
First Posted 12 Feb 2004
Views 69,752
Bookmarked 44 times

How to Create Text Image on the fly with ASP.NET

By | 12 Feb 2004 | Article
Shows you how to display an image with a text written on it to prevent users from copy-pasting.

Sample Image - createTextImage.gif

Introduction

Have you ever wondered how to dynamically create a text image? Similar to those shown on Yahoo! Groups for manual verification whenever you want to join a new group? The code sample shows you how to do just that in ASP.NET, making use of Microsoft's GDI+ library.

I believe the code is quite easy to understand for those familiar with System.Drawing namespace, so I won't explain much. If you look at the online demo and examine the sample code below, I'm sure you'll pretty much grasp everything...

There may be other uses of generating text images, I'm not sure for what else, but I'm sure it's something that won't allow the user to copy-paste text!

The online demo is provided here.

...and here is the .aspx file for it (in C#):

<%@ Page Language="C#" trace="false" Explicit="true" aspcompat="true" Debug="true" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<%@ Import Namespace="System.Drawing.Text" %>
<%@ Import Namespace="System.Drawing.Drawing2D" %>

<script runat="server">
//-------------------------------------
// fonter.net v1.0
//-------------------------------------
// Text Images On the Fly using ASP.Net
// Written in C# and GDI+ library
//-------------------------------------
// (C) Zeddy Iskandar, 2003-onwards.
// Provided as-is, author is not
// responsible for anything.
//------------------------------------- 

public void Page_Load(object sender, System.EventArgs e)
{
   if (Request.HttpMethod == "POST")
   {
    string text = Request.Form.Get("text");
    int textLength = text.Length;
    int fontSize = Convert.ToInt32(Request.Form.Get("fontsize"));
    int orientation = Convert.ToInt32(Request.Form.Get("orientation"));
    int antialias = Convert.ToInt32(Request.Form.Get("antialias")); 

    // Set canvas width & height
    int width; 
    int height;
    if (orientation == 1)
    {
     width  = (fontSize * textLength) - ((textLength * fontSize)/3);
     height = fontSize + 20;
    }
    else
    {
     width  = fontSize + 20;
     height = (int)(fontSize * textLength * 1.5);
    } 

    // Initialize graphics
    RectangleF rectF =new RectangleF(0, 0, width, height);
    Bitmap pic = new Bitmap(width, height, PixelFormat.Format24bppRgb);
    Graphics g = Graphics.FromImage(pic);
    g.SmoothingMode = SmoothingMode.AntiAlias;
    if (antialias == 1) g.TextRenderingHint = TextRenderingHint.AntiAlias; 

    // Set colors
    string fgColor = Request.Form.Get("fontcolor");
    string bgColor = Request.Form.Get("bgcolor");
    Color fontColor = Color.FromName(fgColor);
    Color rectColor = Color.FromName(bgColor);
    SolidBrush fgBrush = new SolidBrush(fontColor);
    SolidBrush bgBrush = new SolidBrush(rectColor); 

    // Rectangle or ellipse?
    int bound = Convert.ToInt32(Request.Form.Get("bound"));
    if (bound == 1)
    {
     g.FillRectangle(bgBrush, rectF);
    }
    else
    {
     g.FillRectangle(new SolidBrush(Color.White), rectF);
     g.FillEllipse(bgBrush, rectF);
    } 

    // Load font
    string fontName = Request.Form.Get("fontname") + ".ttf";
    PrivateFontCollection privateFontCollection = new PrivateFontCollection();
    privateFontCollection.AddFontFile(Server.MapPath("./") + fontName); 
    FontFamily fontFamily = privateFontCollection.Families[0]; 

    // Set font style
    int fontStyle = Convert.ToInt32(Request.Form.Get("fontstyle"));
    FontStyle style = FontStyle.Regular;
    switch (fontStyle)
    {
     case 2:
      style = FontStyle.Bold;
      break; 

     case 3:
      style = FontStyle.Italic;
      break; 

     case 4:
      style = (FontStyle.Bold) | (FontStyle.Italic);
      break; 

     case 5:
      style = FontStyle.Strikeout;
      break; 

     case 6:
      style = FontStyle.Underline;
      break;
    }
    Font font = new Font(fontFamily, fontSize, style, GraphicsUnit.Pixel); 

    // Set font direction & alignment
    StringFormat format = new StringFormat();
    int reverse = Convert.ToInt32(Request.Form.Get("reverse"));
    if (reverse == 1 && orientation == 1)
    {
     format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
    }
    else if (reverse == 1 && orientation > 1)
    {
     StringBuilder temp = new StringBuilder();
     for (int i = textLength-1; i >= 0; i--)
     {
      temp.Insert((textLength-1) - i, text[i]);
     }
     text = temp.ToString();
    } 
    if (orientation > 1)
    {
     rectF.X = width/4;
     rectF.Width = fontSize - (fontSize/4);
    } 
    int alignment = Convert.ToInt32(Request.Form.Get("alignment"));
    if (alignment == 1)
    {
     format.Alignment = StringAlignment.Near;
    }
    else if (alignment == 2)
    {
     format.Alignment = StringAlignment.Center;
    }
    else
    {
     format.Alignment = StringAlignment.Far;
    }
    format.LineAlignment = StringAlignment.Center; 

    // Draw any drop-shadow
    int dropShadow = Convert.ToInt32(Request.Form.Get("dropshadow"));
    if (dropShadow > 0)
    {
     Color shadowColor = Color.FromName(Request.Form.Get("shadowcolor"));
     switch(dropShadow)
     {
      case 1:
       rectF.Offset(-3, -3);
       g.DrawString(text, font, new SolidBrush(shadowColor), rectF, format);
       rectF.Offset(+3, +3);
       break; 

      case 2:
       rectF.Offset(+3, -3);
       g.DrawString(text, font, new SolidBrush(shadowColor), rectF, format);
       rectF.Offset(-3, +3);
       break; 

      case 3:
       rectF.Offset(-3, +3);
       g.DrawString(text, font, new SolidBrush(shadowColor), rectF, format);
       rectF.Offset(+3, -3);
       break; 

      case 4:
       rectF.Offset(+3, +3);
       g.DrawString(text, font, new SolidBrush(shadowColor), rectF, format);
       rectF.Offset(-3, -3);
       break;
     }
    } 

    // Finally, draw the font
    g.DrawString(text, font, fgBrush, rectF, format); 
    Response.ContentType = "image/jpeg";
    pic.Save(Response.OutputStream, ImageFormat.Jpeg); 

    // Dispose objects
    pic.Dispose();
   }
   else
   {
    Response.ContentType = "text/html";
    Response.Write("<html><body>");
    Response.Write("fonter.net v1.0 <br> Create Text Images On-the-Fly <br>");
    Response.Write("(C)2003-onwards, Zeddy Iskandar");
    Response.Write("</body></html>");
   }
}
</script>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

zeddy

Web Developer

Indonesia Indonesia

Member

Zeddy Iskandar, computer science student. Writes freewares on free time. Regularly rambles on his blog. Likes to experiment on emerging software technologies.
 
www.zedilabs.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 1 Pinmembermahdikiani19:25 19 Jul '10  
GeneralNot bad PinmemberTony Truong8:38 23 Mar '04  
QuestionHave you seen?? PinmemberFergal Boden4:57 13 Feb '04  
AnswerRe: Have you seen?? PinsussAnonymous5:04 13 Feb '04  
GeneralRe: Have you seen?? PinmemberColin Angus Mackay14:14 13 Feb '04  
GeneralRe: Have you seen?? PinsussAnonymous18:09 13 Feb '04  
AnswerRe: Have you seen?? PineditorNick Parker8:43 14 Feb '04  
AnswerRe: Have you seen?? PinmemberPaul Ingles8:05 17 Feb '04  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 13 Feb 2004
Article Copyright 2004 by zeddy
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid