2011年8月3日 星期三

[.NET] 生成驗證碼圖片

這是登入或發文時,常用的生成驗證碼圖片程式。
checkCode 是要生成圖片的亂數數字或英文

<ex> "2657" or "rfyj"



    public static void CreateImage(string checkCode)
    {
        int iwidth = (int)(checkCode.Length * 11);
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 18);
        Graphics g = Graphics.FromImage(image);
        Font f = new System.Drawing.Font("Arial", 12, System.Drawing.FontStyle.Bold);
        Brush b = new System.Drawing.SolidBrush(Color.Silver);
        //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
        g.Clear(Color.Indigo);
        g.DrawString(checkCode, f, b, 2, 0);
        Pen blackPen = new Pen(Color.Brown, 2);
        Random rand = new Random();
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        System.Web.HttpContext.Current.Response.ClearContent();
        System.Web.HttpContext.Current.Response.ContentType = "image/Jpeg";
        System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
    }

沒有留言:

張貼留言