用asp.net技术vb.net语言建立一个web form ,实现将文本框中的内容转换成GIF图像。
首先一个web fom 在每次被请求后都需要执行form_load事件代码,事件代码和http的get 和 post请求之间的代码不同,正确的.net术语是IsPostBack,表示web form 已经提交给服务器。即如果IsPostBack=true 说明用户至少浏览过webform一次。
在此应用中,如果需要捕获用户在文本框中输入的文本,则代码要能够进入到if结构的底部。
page_load事件代码如下:
imports system.drawing.text
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' ページを初期化するユーザー コードをここに挿入します。
If Not IsPostBack Then
Response.Write("page before posting")
Else
'pageset Response.ContentType is image/gif because browser need to know how to explain this response
Response.ContentType = "image/gif"
'call the getimage() to convert the bmp file to gif file ,把包含gif文件 的数据流写入显示图像的浏览器
getimage(TextBox1.Text).Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
'send the current output in buffer to the client ,and stop run the page,and invoke Application_EndRequest event.
Response.End()
End If
End Sub
'-----------------------------------------
'create a bmp file,the content of textbox's backcolor is black,fontcolor is yellow
'下面的函数将用户在web form 中输入的文本创建一个bmp文件(黄色文本,黑色背景)
'---------------------------------------
Public Function getimage(ByVal s As String) As Bitmap
Dim b As Bitmap = New Bitmap(1, 1)
'creat a font object
Dim afont As Font = New Font("Times New romah", 10, System.Drawing.GraphicsUnit.Point)
'creat a graphic class to measure the text width
Dim agraphic As Graphics = Graphics.FromImage(b)
'resize the bitmap
b = New Bitmap(CInt(agraphic.MeasureString(s, afont).Width), CInt(agraphic.MeasureString(s, afont).Height))
agraphic = Graphics.FromImage(b)
agraphic.Clear(Color.Black)
agraphic.TextRenderingHint = agraphic.TextRenderingHint.AntiAlias
agraphic.DrawString(s, afont, New SolidBrush(Color.Yellow), 0, 0)
agraphic.Flush()
Return b
End Function
强调:1.该函数返回的时windows为图图像。而运行后的web form 返回的时GIF格式的图像。 即VB.NET可以完成从bmp图像格式到gif图像格式的转换。
上面的代码写完后,按F5,IDE打开一个新的浏览器实体(它是发送前生成的web form)。然后再文本框中输入内容,按回车提交表单,服务器就会在大小合适的gif图片中包含输入的文本 作为响应(发送后生成的web form)。
可以发现短短10行就建立了bmp图片,没有API调用,没有特殊声明语句,没有内存管理,没有调用DLL等就可以工作了。