ASP.NET 页面中的位图图像显示奇怪的字符

Bitmap image in ASP.NET page shows strange characters

我有一个包含以下代码的 .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>

但是页面上显示的是垃圾文字——奇怪的字符,如下:

GIF89a����3f����++3+f+��+��+UU3UfU��U��U����3��f��������3��f���� ����3�fՙ������3��f{��a����q��4��w����k����[�������������� ����럿��<�� !lQ@;

如何让图像正确显示? (最终,我想将图像放在 table 单元格中)

使用 .aspx 页面在处理器使用方面相当昂贵 - "page lifecycle" 涉及多个事件,例如 Page_Load - 与你需要的相比,它只是发送一个 Content-Type(当然还有其他一些 headers)和数据。

如果您使用 .aspx 页面,则必须清除已经为您生成的 headers,否则浏览器将被告知接收类似 "text/html".[=13 的内容=]

作为 mock-up,我使用以下代码创建了一个处理程序 "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=""> 的方式为图像使用 URL。

更多 up-to-date 的方式,以及大量的解释,请参阅 Back to Basics: Dynamic Image Generation, ASP.NET Controllers, Routing, IHttpHandlers, and runAllManagedModulesForAllRequests