Jun 20, 2007

C# : Drawing a Pie Chart and saving as jpeg

////Namespace:
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;

////Create canvas and fill the background
Bitmap objBitmap;
Graphics objGraphics;

objBitmap = new Bitmap(400, 440);
objGraphics = Graphics.FromImage(objBitmap);


objGraphics.Clear(Color.White);

////Draw the pie and fill
Pen p=new Pen(Color.Yellow,0);
Rectangle rect=new Rectangle(10,10,280,280);
objGraphics.DrawEllipse(p,rect);

Brush b1=new SolidBrush(Color.Red);
Brush b2=new SolidBrush(Color.Green);
Brush b3=new SolidBrush(Color.Blue);
objGraphics.FillPie(b1, rect, 0f, 60f);
objGraphics.FillPie(b2, rect, 60f, 150f);
objGraphics.FillPie(b3, rect, 210f, 150f);

////Draw font
FontFamily fontfml = new FontFamily(GenericFontFamilies.Serif);
Font font = new Font(fontfml, 16);
SolidBrush brush = new SolidBrush(Color.Blue);
objGraphics.DrawString("Drawing Graphics", font, brush, 70, 300);

////Export and save to picture
objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
objBitmap.Save(Server.MapPath("x.jpg"), ImageFormat.Jpeg);

////End drawing
objBitmap.Dispose();
objGraphics.Dispose();