Creating Image Free Gradient Buttons in C#

Introduction

This article shall describe a simple tool you can build and use to create the CSS to apply a gradient overlay to buttons, divs, or whatever you like, in an ASP.NET or just plain HTML project. The tool accepts a gradient overlay and background color inputted by the user and it emits the CSS required to render the effect on a web page. The download includes the code for the tool itself as well as a simple demo website showing the output at work.

GrdBtn1.gif

Figure 1: Gradient Button Tool in Use

The CSS generated by the tool may be used to define, for example, the normal appearance of a button, the button under hover, and the button once activated. One may copy and paste the CSS into the appropriate classes in a style sheet to support the appearance of different elements of the page including buttons, banners, or whatever you think might look better with a gradient effect applied to it.

The tool converts the overlay image to a base 64 string; the advantage being that once the user has obtained the CSS, there is no separate image to download and so the CSS file itself is all that is required; multiple separate image file downloads can eliminated within a single project.

GrdBtn2.gif

Figure 2: Demo Website with Buttons and a Banner Styled Using the Tool

In order to use the tool, it is necessary to first create the gradient. I used Expression Design to accomplish that task. I start by adding identical two rectangles to a new project; the height of the rectangles are set to be equal and should be the same height as you intend for the item you are styling. I offset the rectangles horizontally, set the border to nothing. I set the lower image to the background color and apply a gradient effect to the upper image as shown in the following image (except for leaving the border visible to illustrate the presence of two rectangles).

GrdBtn3.gif

Figure 3: Figuring Out the Gradient in Expression Design

For the gradient, I first change the gradient orientation to vertical from the default horizontal. I then set one end of the gradient to be transparent and the other to a suitable color (which will depend on the background color to some extent). Once I am satisfied with the appearance, I export a slice 1 pixel wide out to a temp folder.

GrdBtn4.gif

Figure 4: Exporting a 1 pixel wide slice in Expression Design

Once the slice has been exported, I can use the tool to generate my CSS for me and to pack the image into that CSS. You should only do this with a very small image such as the 1 pixel wide slice; converting large images to a Base 64 string and embedding that into the CSS does not help out much.

The tool itself is simple enough; first load the gradient into the Image File field using a file open dialog triggered from the Browse button. Then set the background color using the color picker launched by clicking the Set Background color button. Lastly, click the Generate CSS button at the bottom of the page to generate the CSS required to create the appearance. The CSS will be shown in this format:

background: #000080 url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAfCAYAAAAmyadiAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAFxE
AABcRAcom8z8AAABESURBVBhXrYwxDoAwDMQuzsz/X8mUDBSpPShvYLFkWbIkOfvqg4wsbDeWi4j4tCAp1r2aOWcxxihOna23wh5s6EfsnR+8nSVffqczwQAAAABJ
RU5ErkJggg==") repeat-x;

This CSS fragment can then be added to your CSS to supply the gradient background with no separate image files required; for example, if we have a command button class, we could use the tool to create separate background appearances for the normal, hover, and active states:

/* button style*/
.commandbutton{
  color:#FFFFFF;
  border-radius:5px;
  -moz-border-radius:5px;
  -webkit-border-radius:5px;
  border:0px;
  font-size:1em;
  text-align:center;
  height:30px;
  width:100px;
  padding:5px;
background: #000000 url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAfCAYAAAAmyadiAAAAAXNSR0IArs4c6QAAAARnQU1BAAC
xjwv8YQUAAAAJcEhZcwAAFxEAABcRAcom8z8AAABESURBVBhXrYwxDoAwDMQuzsz/X8mUDBSpPShvYLFkWbIkOfvqg4wsbDeWi4j4tCAp1r2aOWcxxihOn
a23wh5s6EfsnR+8nSVffqczwQAAAABJRU5ErkJggg==") repeat-x;
}

.commandbutton:hover{  background:#F5170C url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAfCAYAAAAmyadiAAAAAXNSR0IArs4c6QAAAARnQU1BAACx
jwv8YQUAAAAJcEhZcwAAFxEAABcRAcom8z8AAABESURBVBhXrYwxDoAwDMQuzsz/X8mUDBSpPShvYLFkWbIkOfvqg4wsbDeWi4j4tCAp1r2aOWcxxihOna
23wh5s6EfsnR+8nSVffqczwQAAAABJRU5ErkJggg==") repeat-x;
}

.commandbutton:active{
  border-right:#FFF 2px solid;
  border-bottom:#FFF 2px solid;
  border-left:#000000 2px solid;
  border-top:#000000 2px solid;  background:#2B315A url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAfCAYAAAAmyadiAAAAAXNSR0IArs4c6QAAAARnQU1BAACx
jwv8YQUAAAAJcEhZcwAAFxEAABcRAcom8z8AAABESURBVBhXrYwxDoAwDMQuzsz/X8mUDBSpPShvYLFkWbIkOfvqg4wsbDeWi4j4tCAp1r2aOWcxxihOna
23wh5s6EfsnR+8nSVffqczwQAAAABJRU5ErkJggg==") repeat-x;
}

This bit of CSS would render out per the following example images:

GrdBtn5.gif

Figure 5: Command Button class

GrdBtn6.gif

Figure 6: Command Button Hover

GrdBtn7.gif

Figure 7: Command Button Active

Getting Started

There are two solutions in the download; the first is the tool itself and it is entitled, "Base64Gen". The second project is entitled, "" and it demonstrates the output of the tool as used in a website.

The first "Base64Gen" project contains three forms, "about" which is an about box, "instructions" which provides some simple instructions for using the tool, and the last, "main" is the actual tool. All code required by the tool is contained in the main.cs file. The about box and instructions forms are not relevant to this project and so will be not be described herein.

GrdBtn8.gif

Figure 8: Base64Gen Solution

The second solution is an ASP.NET web forms project containing a single web page displaying a banner and a few buttons styled using the tool. It also contains a CSS file used to contain the styles built around the CSS emitted by the tool.

GrdBtn9.gif

Figure 9: Gradient Button Test Solution

First Solution – Base64GEn:

Code: Main.cs

Main.cs is the tool. It contains the code needed to load the overlay image, set the background color, and to generate the CSS. The code is annotated and should be self-explanatory:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Base64Gen
{
    public partial class main : Form
    {
        // form variables
        private string imageFilePath;
        private Color backColor;
        private string hexColor;

        // default constructor
        public main()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Open an image file - this should be a slice of a gradient, 
        /// 1px wide and at whatever height is needed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenImage_Click(object sender, EventArgs e)
        {
            // configure open file dialog
            openFileDialog1.Title = "Source Image File";
            openFileDialog1.Filter = "png files (*.png)|*.png";
            openFileDialog1.FileName = string.Empty;

            // return if user cancels dialog
            if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
                return;

            // get the path to the image file
            string sFilePath = openFileDialog1.FileName;

            // make sure the string has content
            if (String.IsNullOrEmpty(sFilePath))
            {
                MessageBox.Show("File path does not exist", "File");
                return;
            }

            // make sure the file exists
            if (System.IO.File.Exists(sFilePath) == false)
            {
                MessageBox.Show(String.Format("File {0} does not exist", sFilePath), 
                 "Missing File");
                return;
            }

            // update the display to show the file path and set the form
            // variable imageFilePath to the file path
            imageFilePath = sFilePath;
            txtImgFile.Text = imageFilePath;
        }

        /// <summary>
        /// Exit the application upon user request
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        /// <summary>
        /// Convert the image to a base 64 string
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConvert_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(imageFilePath))
            {
                MessageBox.Show("Invalid or missing file name, please select a PNG 
                 file to continue.", "Missing Image File");
            }
            else
            {
                txtBase64.Text = GetBase64String();
            }
        }

        /// <summary>
        /// Create a CSS snippet to set the background to the selected color
        /// with the gradient image file overlay 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGenCSS_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("background: " + hexColor + " url(\"data:image/png;base64," + 
                 GetBase64String() + "\") repeat-x;");
            txtBase64.Text = sb.ToString();
        }

        /// <summary>
        /// Conver the image to a base 64 string so that it can be 
        /// embedded into the CSS file
        /// </summary>
        /// <returns></returns>
        private string GetBase64String()
        {
            try
            {
                // set a string pointing to the file to be converted
                string fileToConvert = imageFilePath;

                // get the length of the file
                FileInfo fInfo = new FileInfo(fileToConvert);
                long numBytes = fInfo.Length;

                // open/read file into a filestream
                FileStream fStream = new FileStream(fileToConvert,
                    FileMode.Open, FileAccess.Read);

                // get a binary reader pointed at the 
                // filestream
                BinaryReader br = new BinaryReader(fStream);

                // get a byte array from the binary reader
                byte[] data = br.ReadBytes((int)numBytes);
                br.Close();

                // convert the byte array to a base 64 string
                string base64String = Convert.ToBase64String(data);
                txtBase64.Text = base64String;

                // clean up
                fStream.Close();
                fStream.Dispose();

                // return the string
                return base64String;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
                return string.Empty;
            }
        }

        /// <summary>
        /// Display the about box
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aboutThisBase64GenToolStripMenuItem_Click(object sender, 
                 EventArgs e)
        {
            about f = new about();
            f.ShowDialog();
        }

        /// <summary>
        /// User a color dialog to set the background color
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHoverColor_Click(object sender, EventArgs e)
        {
            DialogResult result = colorDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                // get the background color from the dialog and display
                // the selected color by setting the picturebox background
                // color to the selected color
                backColor = colorDialog1.Color;
                pboxBackground.BackColor = backColor;

                // convert backcolor to hex and format a hex string
                string hex = string.Format("0x{0:X8}", backColor.ToArgb());
                hexColor = "#" + hex.Substring(hex.Length - 6, 6);

                lblColor.Text = "Background Color:  " + hexColor;
            }
        }

        /// <summary>
        /// Display some simple instructions for how to use the 
        /// program
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void howToUseThisProgramToolStripMenuItem_Click(object sender, 
                 EventArgs e)
        {
            instructions f = new instructions();
            f.Show();
        }

    }
}

Second Solution - Gradient Button Test

This solution contains a single asp.net web forms application with a single web page (default.aspx) and a single CSS style sheet. The gradients used on the web page were generated using the tool and the CSS fragments were placed into classes in the style sheet and applied to elements in the web form.

Summary

The article provides instructions for creating a simple tool that can be used to help define imageless CSS background styles that may be used to style button, banners, and so forth on a web page. The tool may be used in ASP.NET with web forms or it may be used with a straight HTML based project. Building the styles without requiring separate and multiple image file downloads can improve performance slightly by eliminating the additional file downloads.


Similar Articles