asp.net验证码生成

验证码生成:ValiImage.ashx

using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Drawing;
using System.IO;
using System.Web.SessionState;

namespace TestWeb
{
    /// <summary>
    /// 简单的验证码
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ValiImage : IHttpHandler,IRequiresSessionState
    {
        #region 全局变量

        private int imgWidth = 0;
        private int imgHeight = 0;
        private int templength = 0;
        private string tempString = string.Empty;
        private static Random rand = new Random();

        #endregion

        public ValiImage()
        {
            imgWidth = 120;
            imgHeight = 30;
            templength = 10;
            tempString = "abcdefghijklmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
        }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/JPEG";
            DrawImage();
        }

        //生成随即文字
        public string GetRandString()
        {
            string retrunString = string.Empty;
            for (int i = 0; i < templength; i++)
            {
                retrunString += tempString[rand.Next(tempString.Length)];
                i++;
            }

            //寫入session
            HttpContext.Current.Session["ValiString"] = retrunString;
            HttpContext.Current.Request.Cookies.Remove("ValiString");

            //寫入Cookie
            HttpCookie valiCookie = new HttpCookie("ValiString", retrunString);
            valiCookie.Expires = DateTime.Now.AddHours(2);
            HttpContext.Current.Response.Cookies.Add(valiCookie);
            return retrunString;
        }

        //绘出图片
        public void DrawImage()
        { 
            Bitmap bitmap = new Bitmap(imgWidth, imgHeight);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.Clear(Color.White);

            //字體與大小
            Font font = new Font("Arial", 24.0f);
            graphics.DrawString(GetRandString(), font, Brushes.Gray, 1.0f, 1.0f);

            //噪点
            for (int i = 0; i < 100; i++)
            {
                graphics.FillEllipse(Brushes.LightSalmon, rand.Next(imgWidth), rand.Next(imgHeight), 2, 2);
            }

            //法线
            for (int i = 0; i < 10; i++)
            {
                Point[] linePoint = new Point[]
                {
                  new Point(rand.Next(imgWidth),rand.Next(imgHeight)),
                  new Point(rand.Next(imgWidth),rand.Next(imgHeight)),
                  new Point(rand.Next(imgWidth),rand.Next(imgHeight)),
                  new Point(rand.Next(imgWidth),rand.Next(imgHeight)),
                  new Point(rand.Next(imgWidth),rand.Next(imgHeight))
                };

                graphics.DrawLines(Pens.LightBlue, linePoint);
                i++;
            }
            graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphics.Save();
            MemoryStream ms = new MemoryStream();
            bitmap.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);

            //http方式輸出图片
            HttpContext.Current.Response.BinaryWrite(ms.GetBuffer());

            ms.Flush();
            ms.Dispose();
            font.Dispose();
            bitmap.Dispose();
            graphics.Flush();
            graphics.Dispose();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

页面使用:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWeb._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <img src="valiimage.ashx?<%Response.Write(DateTime.Now.Ticks);%>" onclick="this.src = 'valiimage.ashx?'+Math.random();" />
    </div>
    </form>
</body>
</html>


原文地址:https://www.cnblogs.com/hanwest/p/2881891.html