Creating Graphics with XML

This article shows how to create images on the fly and uses XML to specify the properties of the images.

The idea was to be able to create images for buttons on a website. The buttons would simply have a word inside them so it is pretty straightforward. However the interesting approach is to specify the details of the graphics using an XML schema. By doing so I can specify different combinations of colours and words etc. In my program I hard code the XML string into the code direct but it could just as easily be passed in from a command prompt or the program could be changed to a web service etc.

In short the program at the very minimum shows how easy it is to parse XML. You will see that by using data in XML you can in effect chop off a branch of the XML tree and then loop through all the data in just that branch. Once done, you go back and get the next branch and so on.

This code was written with Visual Studio.NET RTM.

//Written 6th April 2001 by John O'Donnell - [email protected]
//Parses an XML string and uses the infortion to create gif files.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Xml;
namespace CreateGif
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
static void Main(string[] args)
//string xmlstring = args[0].ToString();
string xmlstring="<wordlist>
<Btransparent> true </Btransparent>
Console.WriteLine("Creating Graphics");
XmlDocument xmldoc = new XmlDocument();
XmlNodeList items = xmldoc.GetElementsByTagName("word");
for (int i=0;i<items.Count;i++)
string title=xmldoc.GetElementsByTagName("Title").Item(i).InnerText;
string font=xmldoc.GetElementsByTagName("Font").Item(i).InnerText;
int width=Convert.ToInt32(xmldoc.GetElementsByTagName("Width").Item(i).InnerText);
int height=Convert.ToInt32(xmldoc.GetElementsByTagName("Height").Item(i).InnerText);
string color=xmldoc.GetElementsByTagName("Color").Item(i).InnerText;
string bcolor=xmldoc.GetElementsByTagName("Bcolor").Item(i).InnerText;
bool btransparent=Convert.ToBoolean(xmldoc.GetElementsByTagName("Btransparent").Item(i).InnerText);
public static void CreateGraphic (string word, int width, int height, string font,string color,string bcolor,bool btransparent)
Console.WriteLine("Creating graphic for word : " + word);
SolidBrush brush = new SolidBrush(Color.FromName(color));
Bitmap pattern = new Bitmap(width,height);
Graphics g = Graphics.FromImage(pattern);
//find a font size that will fit in the bitmap
bool foundfont=false;
int fontsize=50;
SizeF sizeofstring;
//find a font size that will fit in the bitmap
Font fc = new Font(font, fontsize, System.Drawing.FontStyle.Bold);
sizeofstring=new SizeF(width,height);
if (sizeofstring.Width<pattern.Width)
if (sizeofstring.Height<pattern.Height)
g.DrawString(word, fc, brush,1,1);
if (btransparent==true)
pattern.Save("c:\\Graphics\\" + word + ".jpeg",ImageFormat.Jpeg);

Similar Articles