網站驗證碼圖片生成類

@zgcwkj  2019年01月11日

分類:

代碼 其它 

C# 驗證碼生成代碼,生成樣式

依賴:生成隨機的字符類

生成的圖片:

001.png

源代碼:

/// <summary>
/// 驗證碼工具
/// </summary>
public class ValidateCode
{
    private string validateCode = "";
    private string validateColor = "FFFFFF";

    /// <summary>
    /// 實例驗證碼
    /// </summary>
    /// <param name="length">驗證碼長度</param>
    public Tools_ValidateCode(int length = 4)
    {
        validateCode = new RandomCode(true, true).GoRandom(length);
    }

    /// <summary>
    /// 獲取驗證碼
    /// </summary>
    /// <returns></returns>
    public string GetValidate()
    {
        return validateCode;
    }

    /// <summary>
    /// 背景顏色 不傳參數時為隨機
    /// </summary>
    /// <param name="color"></param>
    public void GetColor(string color = "")
    {
        if (color == "") validateColor = new Tools_RandomCode(true).GoRandom(6); else validateColor = color;
    }

    /// <summary>
    /// 獲取圖片
    /// </summary>
    public byte[] GetImage()
    {
        Bitmap image = new Bitmap(validateCode.Length * 20, 35);
        Graphics g = Graphics.FromImage(image);

        try
        {
            WebColorConverter ww = new WebColorConverter();
            g.Clear((Color)ww.ConvertFromString("#" + validateColor));
            Random random = new Random();

            //畫圖片的背景噪音線
            for (int i = 0; i < 12; 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.LightGray), x1, y1, x2, y2);
            }

            Font font = new Font("Georgia", 20, FontStyle.Bold | FontStyle.Italic);
            LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.Gray, 1.2f, true);
            g.DrawString(validateCode, font, brush, 0, 0);

            //畫圖片的前景噪音點
            for (int i = 0; i < 10; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.White);
            }

            //畫圖片的邊框線
            //g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            MemoryStream ms = new MemoryStream();

            image.Save(ms, ImageFormat.Gif);

            return ms.ToArray();
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
}

使用:

ValidateCode validateCode = new ValidateCode(6);
string random = validateCode.GetValidate();
byte[] img = validateCode.GetImage();

源碼下載:ValidateCode.cs



評論已關閉

Top