Wednesday, November 12, 2008

How to render embedded text in an Image control with ASP.NET

The following quick tutorial will show you how to embed text in an image on an ASP.NET form in 2 simple steps.

The Render form

The first thing you have to do is add a the following form to the root of your website project

RenderImageWithText.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="RenderImage.aspx.vb" Inherits="RenderImage" %>
 
<!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></title>
</head>
<body>
    <form id="form1" runat="server">
 
    </form>
</body>
</html>

and the Code-behind

RenderImageWithText.aspx.vb

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
 
Partial Class RenderImage
    Inherits System.Web.UI.Page
 
    Public Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreRender
        Dim imageFile As String = "image.jpg"
        Dim textToRender As String = "Sample Text"
 
        Dim imageToRender As New Bitmap(Server.MapPath(imageFile))
        Dim g As Graphics = Graphics.FromImage(imageToRender)
        g.SmoothingMode = SmoothingMode.AntiAlias
        g.DrawString(textToRender, New Font("Arial", 12), SystemBrushes.WindowText, 1, 1)
        Response.ContentType = "image/jpeg"
        imageToRender.Save(Response.OutputStream, imageToRender.RawFormat)
    End Sub
 
End Class

 

The background image

the second thing is to add any jpg file to the same location. Just make sure it is at least of some reasonable size and color for the test and has the same name as the value of the imageFile variable (in this case “image.jpg”)

 

Now if you preview the form you will see your text embedded in the image. Obviously you can use this from another form in bunch of different ways. In example you might want to display an email address but prevent it from ending up on some spammer’s list. In this case all you have to do is:

  1. In your RenderImageWithText form - replace the imageFile string value with a Request.QueryString(“Text”)
  2. In your working form add an ImageButton control that looks something like this
<asp:ImageButton ID="ImageButton1" Runat="server" ImageUrl="~/RenderImageWithText.aspx?Text=johndoe@mail.com" />

No comments: