Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Convert Text in to Image using C#

Posted by Viral Sarvaiya on December 13, 2011

.net provide us very good functionality to Create image from text, here is function that return Bitmap and take string as a parameter.


private Bitmap CreateBitmapImage(string TextImage)
{
Bitmap objBmp = new Bitmap(1, 1);

int Width = 0;

int Height = 0;

// Create the Font object for the image text drawing.

Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);

// Create a graphics object to measure the text's width and height.

Graphics objGraphics = Graphics.FromImage(objBmp);

// This is where the bitmap size is determined.

Width = (int)objGraphics.MeasureString(TextImage, objFont).Width;

Height = (int)objGraphics.MeasureString(TextImage, objFont).Height;

// Create the bmpImage again with the correct size for the text and font.

objBmp = new Bitmap(objBmp, new Size(Width, Height));

// Add the colors to the new bitmap.

objGraphics = Graphics.FromImage(objBmp);

// Set Background color

objGraphics.Clear(Color.White);

objGraphics.SmoothingMode = SmoothingMode.AntiAlias;

objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;

objGraphics.DrawString(TextImage, objFont, new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);

objGraphics.Flush();

return (objBmp);
}

Enjoy….

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: