另一个动态 ASP.NET 文本图像






4.77/5 (11投票s)
2004年3月4日
1分钟阅读

129489

1414
另一篇展示如何在 ASP.NET 中从文本动态创建图像的文章。
引言
我看到了一些提交,讨论如何从文本字符串创建图像。这些提交似乎比实际需要的要复杂得多。要从文本字符串创建图像,你只需要调用下面的函数,并将要在图像中绘制的字符串作为参数传递给它。仅此而已。
背景
这是我偶然发现的,我认为其他 Code Project 的读者可能会觉得有用。
使用代码
你唯一需要的函数是下面的 CreateImage()
函数。只需将此函数体添加到你的类或应用程序中,然后在任何想要使用它的地方调用它。就是这么简单。
// Call the CreateImage() function to save the text entered
// into the text box to a stream which will be
// drawn in the CreateImage() function.
CreateImage( txt_Image.Text ).Save( Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Gif );
// This is the CreateImage() function body.
private static Bitmap CreateImage( string sImageText )
{
Bitmap bmpImage = new Bitmap( 1, 1 );
int iWidth = 0;
int iHeight = 0;
// Create the Font object for the image text drawing.
Font MyFont = new Font( "Verdana", 24,
System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point );
// Create a graphics object to measure the text's width and height.
Graphics MyGraphics = Graphics.FromImage( bmpImage );
// This is where the bitmap size is determined.
iWidth = (int)MyGraphics.MeasureString( sImageText, MyFont ).Width;
iHeight = (int)MyGraphics.MeasureString( sImageText, MyFont ).Height;
// Create the bmpImage again with the correct size for the text and font.
bmpImage = new Bitmap( bmpImage, new Size( iWidth, iHeight ) );
// Add the colors to the new bitmap.
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 );
}
确保将此程序集引用添加到页面的顶部。
using System.Drawing.Text;
关注点
我添加了代码,允许用户连接到数据库 (MS Access),以便他们可以从数据库中提取字符串,并将其动态绘制为图像。你需要将 Northwind.mdb 或你自己的数据库添加到项目目录中,并相应地调整连接字符串和查询字符串。这些信息可以在 Button1_Click()
函数中找到。
一旦你的应用程序开始动态绘制图像,你就可以灵活地显示图像并将信息传递给用户。John Corinna 撰写了一些关于如何在图像中传递信息的有趣文章,请参阅 John Corinna。
历史
初始版本 - 1.0 - 2/26/04。