Tuesday, September 18, 2012

How to draw an alphabet as a bitmap image using C#

The following procedure centers a specified alphabet inside a square. Change Color.FromArgb parameters to draw a coloured text.

usage :  DrawAlphabetImage("లు", 28,"Goutami", 32, 32, @"C:\Taa.bmp");


procedure

 /// <summary>
        ///
        /// </summary>
        /// <param name="alphabet">Alphabet as a string</param>
        /// <param name="fontSize">Size Of the font</param>
        /// <param name="width">Image width</param>
        /// <param name="height">Image Height</param>
        /// <param name="fileName">File name to save bmp image</param>


        private void DrawAlphabetImage(string alphabet,int fontSize,string fontFamily, int width,int height,string fileName)
        {
          
           
                    Bitmap bitmap = new Bitmap(1, 1);
                    Font font = new Font(fontFamily, fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
                    Graphics graphics = Graphics.FromImage(bitmap);
                    bitmap = new Bitmap(bitmap, new Size(width, height));
                    graphics = Graphics.FromImage(bitmap);
                    graphics.Clear(Color.White);
                    graphics.SmoothingMode = SmoothingMode.AntiAlias;
                    graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel;
                    using (var format = new StringFormat()
                    {
                        Alignment = StringAlignment.Center,
                        LineAlignment = StringAlignment.Center,
                    })
                    {
                        graphics.DrawString(alphabet, font, new SolidBrush(Color.FromArgb(0, 0, 0)), new Rectangle(0, 0, width, height), format);
                    }

                    graphics.Flush();
                    graphics.Dispose();
                    bitmap.Save(fileName);
        }



Do not forget to add the following using statements

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;