.NET CFVisual Studio .NET 2003.NET 1.1Windows 2000Windows XP移动应用HTML中级开发Visual StudioWindows.NETVisual BasicASP.NET
在 ASP.NET 中创建动态图像






2.89/5 (11投票s)
2004年12月29日
1分钟阅读

120681

1500
本文基于 Manster 的文章,并对其代码进行了 VB.NET 版本的扩展。
介绍/灵感
我一直在网上搜索类似的东西,并找到了 文章,作者是 Manster。 在这篇文章之前,我还找到了一些其他的文章,但它们没有解释如何在不将其保存到磁盘的情况下渲染图像。 在看到这段代码并阅读其他成员在反馈部分提出的问题“如何在图像控件中显示图像”后,我决定完成这件事。
测试应用程序
- 非常简单,只需提取文件并创建一个映射到提取目录的“testing”Web 应用程序。
或者
- 将 Default.* 和 ImageGenerator.* 文件添加到您现有的 Web 应用程序中。 只需要在浏览器中输入 URL 即可。
使用代码
正如我所说,本文基于 Manster 的文章,我不会过多解释动态图像生成的工作原理。 您可以阅读基础文章 这里。
在我的演示项目 (default.aspx) 中,我使用了四个元素。
- 带有默认文本设置的
Image
控件。 Image
控件,用于演示动态图像生成。- HTML 图像元素 (
<img>
)。 - 另一个带有字体大小设置的 HTML 图像元素。
对于 ImageUrl
(Image
控件) / src
(HTML <img>
元素) 的值,只需将要转换为图像的文本作为 HTML 查询字符串传递即可。 例如:
<img src="ImageGenerator.aspx?imgtext=Hello&fontsize=24">
这将生成字体大小为 24 的图像文本“Hello”。 Image
控件的工作方式相同,以相同的方式传递 ImageURL
参数(或直接查看演示代码)。 如果您没有传递查询字符串,则将看到“?”(默认文本)。 默认字体大小设置为 10。
这是我从该站点复制、粘贴并转换为 VB.NET 代码的核心内容。
'The following lines were added as Extention
Dim sImageText As String
Dim iFontSize As Integer
sImageText = Server.UrlDecode(Request.QueryString("imgtext"))
iFontSize = CInt(Server.UrlDecode(Request.QueryString("fontsize")))
'Just fool proofing, in case, "imgtext" parameter is not passed
If sImageText.Trim.Length = 0 Then sImageText = "?"
If iFontSize = 0 Then iFontSize = 12
'Rest of the code goes as is
Dim bmpImage As New Bitmap(1, 1)
Dim iWidth As Integer = 0
Dim iHeight As Integer = 0
'// Create the Font object for the image text drawing.
Dim MyFont As New Font("Verdana", iFontSize, _
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))
Dim MyGraphics As Graphics
MyGraphics = Graphics.FromImage(bmpImage)
'// This is where the bitmap size is determined.
iWidth = MyGraphics.MeasureString(sImageText, MyFont).Width
iHeight = 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.White)
MyGraphics.TextRenderingHint = TextRenderingHint.AntiAlias
MyGraphics.DrawString(sImageText, MyFont, New SolidBrush(Color.Brown), 0, 0)
MyGraphics.Flush()
'Return bmpImage
Response.ContentType = "image/gif" 'Tell browser, what we are sending
bmpImage.Save(Response.OutputStream, ImageFormat.Gif)