Tuesday, August 2, 2011

Dynamically Create Image and write Text Over it

using System.Drawing;

using System.Drawing.Imaging;

using System.Globalization;

///
/// The program.
///
internal class Program
{

private static void Main(string[] args)

{

var chartWidth = 500;

var chartHeight = 200;

Bitmap bitmap = new Bitmap(chartWidth, chartHeight);

Graphics graphics = Graphics.FromImage(bitmap);

using (Font font = new Font("Arial", 20, FontStyle.Bold))

{

var text = string.Format(CultureInfo.InvariantCulture, "Chart Unavailable");

SizeF size = graphics.MeasureString(text, font);

graphics.DrawString(

text,

font,

Brushes.Black,

(((float)chartWidth / 2) - (size.Width / 2)),

(((float)chartHeight / 2) - (size.Height / 2)));

graphics.Dispose();

}

bitmap.Save("test.png", ImageFormat.Png);
//bitmap.Save(memoryStream, ...)

}

}
}

No comments: