Thursday, December 18, 2008

Generating Random Image on a button Click

Generating Random Image on a button Click


public static string GetRandomPassword(int length)
{
Random rand = new Random();
System.Text.StringBuilder password = new System.Text.StringBuilder(length);
for (int i = 1; i <= length; i++)
{
int charIndex;
do {
charIndex = rand.Next(48, 123);

}
while (!((charIndex >= 48 && charIndex <= 57) ||(charIndex >= 65 && charIndex <= 90)|| (charIndex >= 97 && charIndex <= 122)));
// add the random char to the password being built
password.Append(Convert.ToChar(charIndex));
}
return password.ToString();
}


private void GenerateImage(string strRegistrationStr)
{
System.Drawing.Bitmap objBitmap = new Bitmap(150, 30);
Graphics objGraphics = Graphics.FromImage(objBitmap);

//Fore Color and Background of Image
SolidBrush objForeColor = new SolidBrush(Color.White);
SolidBrush objBackColor = new SolidBrush(Color.Black);

objGraphics.FillRectangle(objBackColor, 0, 0, 150, 30);
//Font settings for Image
Font objFont = new Font("Arial", 15);
//Display from 5point from x-axis and 5point from y-axis
Point objPoint = new Point(5, 5);
//Drawing Registration String
objGraphics.DrawString(strRegistrationStr, objFont, objForeColor, objPoint);
//Saving Registration String as Image
//If you dont want image to save
//objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
//otherwise use this
objBitmap.Save(Server.MapPath("RegistrationImg.gif"), ImageFormat.Gif);
//Release object
if (objBitmap != null)
objBitmap.Dispose();
if (objGraphics != null)
objGraphics.Dispose();
}

protected void butRegister_Click(object sender, EventArgs e)
{
GenerateImage(GetRandomPassword(10));
ImgRegistrationStr.ImageUrl = "RegistrationImg.gif";
}





Thanks,
Nitin Sharma