Friday, May 09, 2008

Generate Image from text using C# OR Convert Text in to Image using C#

     Today I learn a new thing, how to generate and image form given text or how to convert text in to image? Dotnet framework provides System.Drawing and System.Drawing.Graphics class which helps us to generate image from text or convert text into image. Below is the code,

   1: private Bitmap CreateBitmapImage(string sImageText)
   2: {
   3:     Bitmap objBmpImage = new Bitmap(1, 1);
   4:  
   5:     int intWidth = 0;
   6:     int intHeight = 0;
   7:  
   8:     // Create the Font object for the image text drawing.
   9:     Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);
  10:  
  11:     // Create a graphics object to measure the text's width and height.
  12:     Graphics objGraphics = Graphics.FromImage(objBmpImage);
  13:     
  14:     // This is where the bitmap size is determined.
  15:     intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
  16:     intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;
  17:  
  18:     // Create the bmpImage again with the correct size for the text and font.
  19:     objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
  20:  
  21:     // Add the colors to the new bitmap.
  22:     objGraphics = Graphics.FromImage(objBmpImage);
  23:  
  24:     // Set Background color
  25:     objGraphics.Clear(Color.White);
  26:     objGraphics.SmoothingMode = SmoothingMode.AntiAlias;
  27:     objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
  28:     objGraphics.DrawString(sImageText, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
  29:     objGraphics.Flush();
  30:  
  31:     return (objBmpImage);
  32: }

Fig (1) - generate image from text or convert text into image 


Happy Programming!!! 

No comments: