我有一个.aspx页面(asp.net),代码如下:
<%@ Page ContentType = "image/gif"%>
<%@ Import Namespace = "System.Drawing" %>
<%@ Import Namespace = "System.Drawing.Imaging" %>
<Script Runat = "Server">
Sub Page_Load
Dim objBitmap As Bitmap
Dim objGraphics As Graphics
objBitmap = New Bitmap(200, 200)
objGraphics = Graphics.FromImage(objBitmap)
objGraphics.DrawLine(new Pen(Color.Red), 0, 0, 200, 200)
objBitmap.Save(Response.OutputStream, ImageFormat.Gif)
objBitmap.Dispose()
objGraphics.Dispose()
End Sub
</Script>
但页面上显示的是垃圾文本 - 奇怪的字符,如下所示:
GIF89a3f ++ 3 + F +++ UU3UfUUU3f3f 3F 3 F {aq4wk [ѻ 럿 &lt; !lQ @;
如何让图像正确显示? (最终,我想将图像放在表格单元格中)
答案 0 :(得分:0)
使用.aspx页面在处理器使用方面非常昂贵 - “页面生命周期”涉及多个事件,例如Page_Load - 与您需要的事件相比,它只是发送内容类型(以及其他一些内容)标题,当然)和数据。
如果您使用.aspx页面,则必须清除已为您生成的标题,否则将告知浏览器接收“text / html”之类的内容。
作为模型,我使用以下代码创建了一个处理程序“GetImage.ashx”:
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Web
Imports System.Web.Services
Public Class Handler1
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "image/png" ' set correct MIME type here '
Using objBitmap As Bitmap = New Bitmap(200, 200)
Using objGraphics As Graphics = Graphics.FromImage(objBitmap)
objGraphics.DrawLine(New Pen(Color.Red), 0, 0, 200, 200)
objBitmap.Save(context.Response.OutputStream, ImageFormat.Png)
End Using
End Using
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return True
End Get
End Property
End Class
可以按照您的意图在浏览器中生成图像。
只需以<img src="http://127.0.0.1/webtest/getimage.ashx" alt="">
的方式使用图片的网址。