首页/C#语言/C#生成图片验证码/

C#生成图片验证码

2013-05-24
795

本文介绍生成C#验证码的方法,可将本方法放在一个 ashx 文件里,并继承自 System.Web.SessionState.IRequiresSessionState 以保存 session 。

using System;
using System.Drawing;
using System.Drawing.Drawing2D;

#region Create
private void Create(string code)
{
    if (code == null || code.Trim() == String.Empty) return;

    Bitmap image = new Bitmap((int)Math.Ceiling((code.Length * 11.5)), 21);
    Graphics g = Graphics.FromImage(image);

    try
    {
        Random random = new Random();
        g.Clear(Color.White);

        for (int i = 0; i < 25; i++)
        {
            int x1 = random.Next(image.Width);
            int x2 = random.Next(image.Width);
            int y1 = random.Next(image.Height);
            int y2 = random.Next(image.Height);

            g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
        }

        //Font font = new Font("Arial", 11, (FontStyle.Bold | FontStyle.Italic));
        Font font = new Font("Arial", 11, (FontStyle.Regular | FontStyle.Bold));
        LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
        g.DrawString(code, font, brush, 2, 2);
        font.Dispose();
        brush.Dispose();

        for (int i = 0; i < 100; i++)
        {
            int x = random.Next(image.Width);
            int y = random.Next(image.Height);

            image.SetPixel(x, y, Color.FromArgb(random.Next()));
        }

        g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        Response.ClearContent();
        Response.ContentType = "image/Gif";
        Response.BinaryWrite(ms.ToArray());
        ms.Dispose();
    }
    finally
    {
        g.Dispose();
        image.Dispose();
    }
}
#endregion
Copyright © 2021 技术探索 All Rights Reserved.