Introduction
I've seen a couple of submissions which address how one can create an image from a text string. These submissions seem to be much more complicated then they need to be. To create an image from a text string, all you have to do is call the function below passing in the string which will be drawn in the image. That's all there is to it.
Background
This was something I stumbled upon and I thought other Code Project readers may find useful.
Using the code
The only function you need is the CreateImage()
function below. Just add this function body to your class or application, then call it wherever you want to use it. It's that easy.
CreateImage( txt_Image.Text ).Save( Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Gif );
private static Bitmap CreateImage( string sImageText )
{
Bitmap bmpImage = new Bitmap( 1, 1 );
int iWidth = 0;
int iHeight = 0;
Font MyFont = new Font( "Verdana", 24,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point );
Graphics MyGraphics = Graphics.FromImage( bmpImage );
iWidth = (int)MyGraphics.MeasureString( sImageText, MyFont ).Width;
iHeight = (int)MyGraphics.MeasureString( sImageText, MyFont ).Height;
bmpImage = new Bitmap( bmpImage, new Size( iWidth, iHeight ) );
MyGraphics = Graphics.FromImage( bmpImage );
MyGraphics.Clear( Color.Navy );
MyGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
MyGraphics.DrawString( sImageText, MyFont,
new SolidBrush( Color.Red ), 0, 0 );
MyGraphics.Flush();
return( bmpImage );
}
Make sure you add this assembly reference to the top of your page.
using System.Drawing.Text;
Points of Interest
I added the code for a user to connect to a database (MS Access), so they can pull a string from the database and have it dynamically drawn as an image. You'll have to add the Northwind.mdb or your own database to the project directory and adjust the connection string and query string accordingly. This information can be found in the Button1_Click()
function.
Once you have your application drawing images dynamically, you have lots of flexibility to display images and pass information to the user. Some interesting articles on how to pass information inside an image were written by John Corinna.
History
Initial version - 1.0 - 2/26/04.