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!!!
Hi Can you tell me how to use about in a website…I measn I wanna put a form where if text is entered it gets converted to image??
TIA
pankajt
hey chirag,
how are you putting source code in WordPress. I tried putting
but this way code looks very clumsy.
What tag have you used for this post.
MP
http://grewal.wordpress.com
Grewal,
I am using Windos live writer and plugins for writting the blog. This plug in writes the code in this format.
Nice article chiragrdarji – well written and works perfectly for me. Thanks.
Hi,
I’m a beginner in C#.
I would like to know how to call this function.
I need to create an image from a text and your function looks like what i need but i dont know how to use it.
Can someone helps me plz ?
Thx !
MemoryStream memStream = new MemoryStream();
objBmpImage.Save(memStream, ImageFormat.Jpeg);
memStream.WriteTo(Response.OutputStream);
Nice article