Ask any ASP developer who has ever tried to dynamically create his own images and he’ll tell you it’s a nightmare. In fact, it’s more than a nightmare. It’s practically hell. The only true solution? Reverting to an expensive, dodgy, third-party control to do the work for you.
With ASP.NET however, you can develop your own dynamic images with ease. Simply create an image object and use the new GDI+ features to add objects to that image, such as text, rectangles, and ellipses. After that, you can simply stream straight back down to the client.
However, covering the graphics features in depth would require at least another two booksï¿½and unfortunately, we don’t have that much room. So, I’m going to share a sample that demonstrates creating a small ‘Empty Karl’s Basket’ button, alongside a little blue and yellow bullet point. It’s the sort of personalized graphic you’ll find on sites such as Amazon.com.
Just add the following code to the Page Load event of a Web form. That Web form will then feed back this image as its output. In other words, your Web browser will recognize the page as a graphic. That means if you wanted to reference the image in an Image control, say, you’d specify the source (the ImageUrl) as being YourWebFormName.aspx.
Here’s the code:
' Create image - you could even load an image ' from a file and edit it in code Dim objBitmap As Bitmap = New Bitmap(120, 30) Dim objGraphics As Graphics = Graphics.FromImage(objBitmap) ' Fill background objGraphics.FillRectangle(New SolidBrush(Color.LightBlue), _ 0, 0, 120, 30) ' Create blue-yellow bullet point objGraphics.FillEllipse(New SolidBrush(Color.Blue), 3, 9, 10, 10) objGraphics.FillEllipse(New SolidBrush(Color.Yellow), 4, 10, 8, 8) ' Draw text next to bullet point objGraphics.DrawString("Empty Karl's Basket", _ New Font("Tahoma", 8), New SolidBrush(Color.Green), 16, 8) ' Send down to client Response.Clear() Response.ContentType = "image/jpeg" objBitmap.Save(Response.OutputStream, _ System.Drawing.Imaging.ImageFormat.Jpeg) ' Tidy up objGraphics.Dispose() objBitmap.Dispose()
At its very least, this code demonstrates passing images back down to your browser via a Web page. Now, all you need to do is brush up on your GDI+ skillsï¿½and the dynamic image generation world is your oyster. For more information and a series of tutorials, use the Help Index to look up ‘images, GDI+’.