There are some nice tutorials on how to display text as an image. Some examples of when you might wish to use something like this is perhaps if you wish to display your email address on a web page, but don't want it to be harvested by spammers; a CAPTCHA for authenticating a real person on log in, or adding a URL to existing images on your site to keep them from being "swiped" by others.
I'm going to demonstrate the last scenario, a simple method that will print text to the bottom left of an image. You could easily alter it to pass in the x and y coordinates of where you wish to add the text, if desired.
Please download the ImageEdit.zip which contains code for both this example and an example of Resizing ASP.NET Images Using GDI+ Dynamically.
Here is what our final image will look like:
In my code-in-front, I have this:<asp:ImageID="Image1"runat="server"/><br/><asp:ButtonID="Button1"runat="server"Text="Button"/>
In the code-behind I make sure to import:
Imports System.Drawing
Imports
You may add this to your Page_Load or a button click event or some method you call:
Dim fileNameFrom AsString = Server.MapPath("~/Images/PiperAtComputer.jpg")Dim fileNameTo AsString = Server.MapPath("~/Images/test2.jpg")
TextOnImage("Programming Is Fun!", fileNameFrom, fileNameTo)
Image1.ImageUrl = "~/Images/test2.jpg"
From the above, you see that to call our TextOnImage method, pass in a path from your root directory.
ProtectedSub TextOnImage(ByVal textString AsString, _ByVal fileNameFrom AsString, _
ByVal fileNameTo AsString)Dim Bmp As Drawing.Bitmap = Drawing.Bitmap.FromFile(fileNameFrom)Using graphicsImage As Graphics = Graphics.FromImage(Bmp)
Dim typeFont AsNew Font("Arial", 8, FontStyle.Bold)' get height of current image
Dim height AsInteger = Bmp.Height
' start string in 2 pixels from left and 15 pixels up from the bottom of the image
Dim leftMargin AsInteger = 2
Dim bottomMargin AsInteger = height - 15
graphicsImage.DrawString(textString, typeFont, Brushes.WhiteSmoke, leftMargin, bottomMargin)
Bmp.Save(fileNameTo, ImageFormat.Jpeg)
Bmp.Dispose()EndSubOther examples show how to create a new image from text.
Dynamic ASP.NET Text Image (C#) - This shows how to take text and display it as an image. Within this article, a reader posts a message how to do this with a transparent background (VB) which he altered after viewing this code (C#). Another readers shows how to display an image in an image control.
Programmatically add text to an image (C#)
May your dreams be in ASP.NET!
P.S. Some other imaging urls of interest:
Displaying Dynamically Generated Images (C#) - I downloaded this zip project and it works with 3.5 framework. The demo zooms and enlarges an image of a pineapple.
Graphics in VB.NET - Articles, Resources, Downloads, Blogs, Book Chapters, Tutorial, Source code
Getting Started with GDI+ in C# Applications
GDI+ in VB.NET Tutorial for Beginners
Opening and viewing Images and Text files
Image Conversion Utility in C#