【问题标题】:Bitmap image in ASP.NET page shows strange charactersASP.NET 页面中的位图图像显示奇怪的字符
【发布时间】:2015-03-13 22:49:22
【问题描述】:

我有一个带有以下代码的 .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����[��������ѻ������ ��럿� �

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

【问题讨论】:

  • 您不需要 .aspx 表单的广泛性来提供图像:.ashx 处理程序会更合适。对于某些情况:Display Image using ashx Handler.
  • 您的问题是您正在向浏览器发送数据,但您没有告诉它什么类型的数据。你得到的不是垃圾或奇怪的字符。您正在让浏览器解释您发送的字节。因为你没有告诉它这是一个 gif 图像,所以你得到了这个。将 Response.ContentType = "image/gif" 信息设置为:msdn.microsoft.com/en-us/library/…

标签: asp.net graphics system.drawing


【解决方案1】:

使用 .aspx 页面在处理器使用方面非常昂贵 - “页面生命周期”涉及多个事件,例如 Page_Load - 与您需要的相比,它只是发送一个 Content-Type(以及其他几个标题,当然)和数据。

如果您使用 .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

它会在浏览器中按您的预期生成图像。

只需以&lt;img src="http://127.0.0.1/webtest/getimage.ashx" alt=""&gt; 的方式使用图像的 URL。

更多最新方法,有大量解释,请参阅Back to Basics: Dynamic Image Generation, ASP.NET Controllers, Routing, IHttpHandlers, and runAllManagedModulesForAllRequests

【讨论】:

  • 谢谢 - 我认为这与标题有关。这个解决方案肯定会创建图像,但我的最终目标是将它放在 TableCell 中。我是 HttpHandlers 的新手,但我怎样才能把它变成一个对象并编写类似的代码:myTblCell.Controls.Add(myImage),而不用摆弄 web.config 文件(其中 myImage 是图形绘图) ?
  • @swabygw 你需要做的就是使用处理程序的 URL,就像你在图像中输入 URL 一样,这样渲染的 HTML 就会像 &lt;img src="http://127.0.0.1/webtest/getimage.ashx" alt=""&gt; 一样结束。跨度>
猜你喜欢
  • 2011-07-10
  • 1970-01-01
  • 2019-03-22
  • 1970-01-01
  • 2021-06-27
  • 2021-06-27
  • 2013-06-24
  • 2011-07-07
  • 2015-05-21
相关资源
最近更新 更多