Search code examples
asp.netgraphicssystem.drawing

Bitmap image in ASP.NET page shows strange characters


I have an .aspx page (asp.net) with the following code:

    <%@ 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>

But what shows up on the page is junk text - strange characters, as follows:

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

How do I get the image to show up correctly? (eventually, I want to place the image within a table cell)


Solution

  • Using an .aspx page is quite expensive in terms of processor usage - the "page lifecycle" involves several events, such as Page_Load - compared to what you need, which is just sending a Content-Type (and just a few other headers, of course) and the data.

    If you used an .aspx page, you would have to clear the headers which have already been generated for you otherwise the browser would be told to receive something like "text/html".

    As a mock-up, I made a handler "GetImage.ashx" with this code:

    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
    

    which generates the image in a browser as you intended.

    Simply use a URL for the image in the fashion of <img src="http://127.0.0.1/webtest/getimage.ashx" alt="">.

    For a more up-to-date way, with plenty of explanation, please see Back to Basics: Dynamic Image Generation, ASP.NET Controllers, Routing, IHttpHandlers, and runAllManagedModulesForAllRequests.