Create a new bitmap image and draw a line

June 08, 2011 - 13:22

Many applications require that images are dynamically created especially for the user in websites. I normaly do this when ploting graphs or adding watermarking on images as they are displayed instead of having numerous duplicated saved images on the server.

In this example the new bitmap is first created by either using a new blank bitmap, or from reading in a bitmap from a local file. Once the bitmap is loaded then the Graphics namespace is used to draw additional items onto the bitmap.

<%@ Import Namespace="system.drawing" %>

Dim newimage As New Bitmap(200, 200)
Dim gr As Graphics = Graphics.FromImage(newimage)
gr.DrawLine(Pens.Red, 0, 0, 50, 50)

As an additional piece of code, once you have the bitmap then you can use binarywrite to write the resulting .jpeg data directly back to the browser, this will then display the bitmap on your webpage when using the link to the .aspx page.

Dim ms As MemoryStream = New MemoryStream
newimage.Save(ms, System.Drawing.Imaging.ImageFormat.jpeg)
Dim b() As Byte = ms.ToArray

The above code can be added onto the end of the page to finally convet the image to a binary array and write back the jpeg image.

© 2011