Click here to Skip to main content
Click here to Skip to main content

Image Generation in Visual Studio 2005

, 5 Aug 2004
Rate this:
Please Sign up or sign in to vote.
An article that demonstrates how one can leverage the ImageGenerator Class to create textual images on the fly

Introduction

Often, the creative group and/or site builders on the project determine that the look and feel needed for a site cannot be handled by mere text and style sheets. This will normally lead to having a number of images that are just text or some text on top of a navigation button. When this occurs the developer could get frustrated with maintenance or site changes because a simple textual change forces the creative designer to get involved again so they can modify or create a new image. If the site is more complex and supports different languages or the images need to be dynamic, the number of buttons and other images gets multiplied.

Leveraging the ImageGenerator class and the DynamicImage web control in ASP.NET 2.0, one can reduce the dependency on the creative department and allow for a more flexible site while still satisfying the branding guidelines. This sample project contains a Default.aspx page that contains a DynamicImage control called diDynamicImage which points to an ImageGenerator file called ImageMaker.asix. ImageMaker.asix reads in the necessary properties and parameters of diDynamicImage and generates an image on the fly. With this architecture the only graphic needed from the creative department would be the background image of the button, and even that is optional.

In order to accommodate the majority of readers out there that don't have Visual Studio 2005 installed I have placed a lot of the code within the article. So hopefully those of you that can't actually work with the solution will get the gist by just reading the article.

Code Walkthrough

DynamicImage Class

The DynamicImage Class renders images from files, databases or code on the requesting browser (MSDN Link). Below is the list of properties and parameters we have specified for the diDynamicImage control.

  • ID - ID of the server control
  • ImageGeneratorURL- The URL of our ImageGenerator .asix file which will build our image on the fly
  • ImageType - Automatic, Jpg, Gif, Bmp, Png
  • Height - Height of the image
  • Width- Width of the image
  • ParameterMode - ImageGenerationStorage (more secure) or QueryString
  • ForeColor - The font color of the text
  • BackColor - The back ground color of the image (only displays if a background image isn't supplied)

-- Custom Parameters --

  • Text - The text that should be displayed
  • Font - The font of the text (e.g. Arial, Kristin ITC)
  • FontSize - Size of the text
  • FontStyle - Style of the font (e.g. Bold, Italic)
  • xPoint - Where the text should be located along the X axis (0 is left most)
  • yPoint - Where the text should be located along the Y axis (0 is top most)
  • Image - Name of the image file that should be used as the background
<asp:DynamicImage ID="diDynamicImage" 
  ImageGeneratorUrl="~/images/ImageMaker.asix" 
  ImageType="Automatic" Height="60px" Width="150px"
  ParameterMode="ImageGenerationStorage" ForeColor="Navy" 
  BackColor="#8080FF" Runat="server">
<Parameters>
<asp:Parameter DefaultValue="Hello World!" Name="Text"></asp:Parameter>
<asp:Parameter DefaultValue="Kristin ITC" Name="Font"></asp:Parameter>
<asp:Parameter DefaultValue="10" Name="FontSize"></asp:Parameter>
<asp:Parameter DefaultValue="Bold" Name="FontStyle"></asp:Parameter>
<asp:Parameter DefaultValue="31" Name="xPoint"></asp:Parameter>
<asp:Parameter DefaultValue="14" Name="yPoint"></asp:Parameter>
<asp:Parameter DefaultValue="pill.jpg" Name="Image"></asp:Parameter>
</Parameters>
</asp:DynamicImage>

ImageGenerator Class:

An ImageGenerator page (.asix file) allows us to dynamically build whatever kind of image we desire. For this article we are just building images that display text but you could easily build an ImageGenerator that helps with reporting or drawing anything as long as it renders an image. Prior to ASP.NET 2.0 you could basically create your own ImageGenerator class by just having an .aspx file stream back the image you are creating, but the new ImageGenerator class available in the next framework release makes our life a little easier.

Our ImageMaker class inherits from the ImageGenerator class and overrides the RenderImage method. The method does the following:

  • Set the image size using the height and width properties of the control calling the class
  • Get the custom parameters from the control
  • Fill the background with either the image passed or a SolidBrush in the color of the BackColor set in the control
  • Draw the text onto the canvas using the text that was passed in by the control
<%@ Image Language="C#" Class="ImageMaker" %>

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public class ImageMaker : System.Web.UI.Imaging.ImageGenerator
{
    protected override void RenderImage(Graphics g)
    {
        //set bounds of the canvas
        int width = (int)Style.Width.Value;
        int height = (int)Style.Height.Value;
        int w = Math.Max(DefaultWidth, width);
        int h = Math.Max(DefaultHeight, height);
        
        //set parameters;    //set parameters        
        string txt = GetParameter("Text","");
        string file = GetParameter("Image","");
        string fnt = GetParameter("Font", "Arial");
        int fntSize = Int32.Parse(GetParameter("FontSize", "12"));
        FontStyle fntStyle = GetParameter(GetParameter("FontStyle", "Regular"));
        int x = Int32.Parse(GetParameter("xPoint", "0"));
        int y = Int32.Parse(GetParameter("yPoint", "0"));

        //fill the background
        //if a file isn't supplied or is supplied incorrectly then
        //the background is painted using the color supplied by property
        try
        {
            if (file.Length > 0)
            {
                //Image image = new Bitmap("C:\\WebSites\\acom1\\images\\" + file);
                Image image = new Bitmap(Server.MapPath("") + "\\" + file);
                TextureBrush bgBrush = new TextureBrush(image);
                g.FillRectangle(bgBrush, g.ClipBounds);
            }
            else
            {
                SolidBrush bgBrush = new SolidBrush(Style.BackColor);
                g.FillRectangle(bgBrush, g.ClipBounds);
            }
        }
        catch (System.Exception e)
        {
            SolidBrush bgBrush = new SolidBrush(Style.BackColor);
            g.FillRectangle(bgBrush, g.ClipBounds);
        }

        //overlay the text
        SolidBrush textcolor = new SolidBrush(Style.ForeColor);
        g.DrawString(txt, new Font(fnt, fntSize,fntStyle), textcolor,x, y);

    }
        

Utility Methods:

I did a little refactoring and extracted some of the parameter retrieval into their own methods. The string GetParameter checks for the parameter in the querystring and then the parameter collection if the querystring was empty. The FontStyle GetParameter method basically converts the FontStyle parameter string into a FontStyle object

 //grab the parameters out of the parameters collection or the querystring
    private string GetParameter(string name, string defaultValue)
    {
        string s = defaultValue;
        if (Parameters.Count == 0)
        {
            string t = Request[name];
            if ((null != t) && (t.Length > 0))
            {
                s = t;
            }
        }
        else
        {
            if (null != Parameters[name])
            {
                s = Parameters[name].ToString();
            }
        }
        return s;
    }
   
    //convert the string style to a FontStyle object
    private FontStyle GetParameter(string inStyle)
    {
        FontStyle fntStyle = FontStyle.Regular;
        switch (inStyle)
        {
            case "Regular":
                fntStyle = FontStyle.Regular;
                break;
            case "Bold":
                fntStyle = FontStyle.Bold;
                break;
            case "Italic":
                fntStyle = FontStyle.Italic;
                break;
            case "Underline":
                fntStyle = FontStyle.Underline;
                break;
            case "Strikeout":
                fntStyle = FontStyle.Strikeout;
                break;
        }
        return fntStyle;
    }
        

Points of Interest

This is really just the tip of the iceberg of what is possible. I wanted to keep it simple and in the intermediate category. Some of my planned uses for this approach (when VS.NET 2005 is out of beta) is to use the new Theme and Skin features as well as resource files to apply different looks and languages to the images being displayed.

To get at the DynamicImage parameters through code you would simply do something like:

  • diDynamicImage.Parameters["Text"].DefaultValue = "Code Behind";.

History

  • 7/29/2004 - article submitted

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

James Coleman
Technical Lead Independent Consultant
United States United States
___________________________
J A M E S C O L E M A N
Director, Technical Services
Linked-In: http://www.linkedin.com/in/jameswcoleman
Blog: ledtalks.wordpress.com
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
QuestionCreating An Image While Making A Signup Form. Pinmembermshariq29-Jun-06 19:40 
QuestionDynamic Image Buttons? PinmemberPete?25-Jan-05 7:27 
AnswerRe: Dynamic Image Buttons? PinsussAnonymous10-Mar-05 7:49 
GeneralRe: Dynamic Image Buttons? PinmemberWhatIsChoam?10-Mar-05 9:01 
QuestionWill MS support this at release? PinmemberLevi.Rosol19-Aug-04 3:09 
AnswerRe: Will MS support this at release? Pinmemberbarrd25-Jul-05 14:00 
GeneralA couple of random questions PinsussAnonymous11-Aug-04 8:50 
GeneralHi PinmemberScoelho11-Aug-04 6:37 
GeneralRe: Hi PinmemberJames Coleman11-Aug-04 6:45 
GeneralCode Edit PinmemberJames Coleman4-Aug-04 5:19 
GeneralThanx! + suggestion... PinmemberArjan Einbu3-Aug-04 23:26 
GeneralRe: Thanx! + suggestion... PinmemberJames Coleman4-Aug-04 3:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 6 Aug 2004
Article Copyright 2004 by James Coleman
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid