Click here to Skip to main content
6,630,289 members and growing! (21,864 online)
Email Password   helpLost your password?
Web Development » Charts, Graphs and Images » Images and multimedia     Intermediate

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

By zeddy

Shows you how to display an image with a text written on it to prevent users from copy-pasting
Windows, .NET, ASP.NET, Visual Studio, Dev
Posted:24 Feb 2004
Views:93,542
Bookmarked:39 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
5 votes for this article.
Popularity: 1.95 Rating: 2.79 out of 5
2 votes, 40.0%
1

2
1 vote, 20.0%
3
1 vote, 20.0%
4
1 vote, 20.0%
5

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 at: http://www.zedilabs.com/dotnet.html

Code

...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" %>

//-------------------------------------
// 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>");
   }
}

Now all you need to create is the corresponding HTML source. The HTML will be quite long as it has to accommodate the different possible color values.

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


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
Occupation: Web Developer
Location: Indonesia Indonesia

Other popular Charts, Graphs and Images articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
Generalgood and usefull work Pinmemberravindraee2420:09 10 Mar '08  
GeneralBarcode Font PinsussAnonymous14:45 26 Jun '05  
GeneralHow can I get rid of the Shadow on the Left side and Top? Pinsussjouin@webfoxmail.com15:31 30 Apr '05  
GeneralRe: How can I get rid of the Shadow on the Left side and Top? PinmemberBamohriz23:32 17 Jun '05  
Generalmy VS + IE hangs when i create images / GDI Pinmemberedelwater13:18 9 Dec '04  
GeneralProper way to get text to fit PinsussAnonymous18:23 1 Jul '04  
GeneralDyanmic Pictures in Custom Control PinmemberKalin Kishkin6:00 25 Feb '04  
GeneralRe: Dyanmic Pictures in Custom Control Pinmemberzeddy20:06 26 Feb '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Feb 2004
Editor: Nishant Sivakumar
Copyright 2004 by zeddy
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project