Pages

Subscribe:

Ads 468x60px

Friday, March 16, 2012

how to convert text string into an image in asp.net using c#

in this web programming tutorial we will learn that how we can convert text string provided by user into an image in asp.net using c#. this will help us to make our own captcha images instead to use third party tools.

HTML Code to get text string from user


    


    

we need to inherit following namespaces in our .cs file
using System.Drawing.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
Now below code will help us to genereate .jpg file from user input string.
protected void btnConvert_Click(object sender, EventArgs e)
{
    string text = txtText.Text.Trim();
    Bitmap bitmap = new Bitmap(1, 1);
    Font font = new Font("Arial", 25, FontStyle.Regular, GraphicsUnit.Pixel);
    Graphics graphics = Graphics.FromImage(bitmap);
    int width = (int)graphics.MeasureString(text, font).Width;
    int height = (int)graphics.MeasureString(text, font).Height;
    bitmap = new Bitmap(bitmap, new Size(width, height));
    graphics = Graphics.FromImage(bitmap);
    graphics.Clear(Color.White);
    graphics.SmoothingMode = SmoothingMode.AntiAlias;
    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
    graphics.DrawString(text, font, new SolidBrush(Color.FromArgb(255, 0, 0)), 0, 0);
    graphics.Flush();
    graphics.Dispose();
    string fileName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".jpg";
    bitmap.Save(Server.MapPath("~/images/") + fileName, ImageFormat.Jpeg);
    imgText.ImageUrl = "~/images/" + fileName;
    imgText.Visible = true;
}

No comments:

Post a Comment