Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Asp.net 2.0 generate image on the fly

Ok, this time I will be straight to work.

- aspx file

<asp:Image ID="Image1" runat="server" /> <!-- only one control to show the image -->

- aspx.vb file

' Importing needed name spaces

Imports System.Drawing.Imaging

Imports System.Drawing

 

Than in page load event I am generating the image and inserting text on it

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

' Creating bitmap and giving size width = 80 and heigh = 50 px

Dim Bitmap As Bitmap = New Bitmap(80, 50)

' Getting the bitmap to use it as graphic image but default the bitmap is black colored

Dim Graphic As Graphics = Graphics.FromImage(Bitmap)

' Creating shaped graphic image in this case rectangle and setting it's background color and size to

' fit the bitmap size

Graphic.FillRectangle(Brushes.Beige, 0, 0, 80, 50)

' Setting font name and size

Dim font As New Font("Arial", 13)

'Using the graphics drawstring property to set our customer text, font, font color and outstepping distances from the top left corner by x an y axis

Graphic.DrawString("my text", font, Brushes.Black, 10, 10)

'Saving the image and choosing its file format

Bitmap.Save(Server.MapPath("image.jpg"), ImageFormat.Jpeg)

'Setting the asp image control ImageUrl property to show us the generated image

Image1.ImageUrl = "~/image.jpg"

End Sub

Hope it helps

P.S.

Any questions are welcome

Ok, here is how to use it with http response

 

'Sending the image in http response

Response.ContentType = "image/jpeg"

'Saving the image and choosing its file format

Bitmap.Save(Response.OutputStream, ImageFormat.Jpeg)

You can do the formatting of html in your response stream

Regards

2 Comments

  • Rather than writing to disk and reading it back, you might be better off writing an IHttpHandler and save directly to the Response stream (after setting the response MIME type).

    ref: http://msdn.microsoft.com/en-us/library/ms228090.aspx

    Raj

  • Saving to a fixed filename looks dodgy.
    If two clients access the page at about the same time, one may attempt to retrieve the image file while another is updating it.

Comments have been disabled for this content.