网页写验证码

换一张按钮实现

<a href="javascript:document.getElementById('ValidateCodeImage').src='ValidateCode.aspx?'+new Date;void(0);">换一张?</a>

点击图片换一张jquery实现

 <script type="text/javascript">
        $(function () {
            $('#ValidateCodeImage').click(function () {
                $(this).attr('src', 'ValidateCode.aspx');
            })
        })
    </script>


第一种方法  前台不用写东西

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Text;

namespace 验证码
{
    public partial class pic : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            System.Drawing.Image img = new Bitmap(100, 30);

            Graphics g = Graphics.FromImage(img);
            this.AddPoint(img, 100);
            string code = this.GenderalCode();
            Font font1=new Font("楷体",20,FontStyle.Italic);
            g.DrawString(code, font1, Brushes.Red, 0, 0);
            this.Response.Clear();
            MemoryStream ms = new MemoryStream();
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            this.Response.BinaryWrite(ms.ToArray());
            this.Response.Flush();
            this.Response.End();
           
           
        }
        private void AddPoint(System.Drawing.Image img, int nums)//加噪点背景
        {
            Bitmap b = img as Bitmap;
            Random rand = new Random();
            for (int i = 0; i < nums; i++)
            {
                b.SetPixel(rand.Next(0, img.Width), rand.Next(0, img.Height), Color.White);
            }
        }
        //生成随机的文字
        private string GenderalCode()
        {
            Random rand = new Random(DateTime.Now.Millisecond);
            StringBuilder sb = new StringBuilder(6);
            for (int i = 0; i < 6; i++)
            {
                sb.Append(rand.Next(0, 9));
            }
            return sb.ToString();
        }
    }
}

在别的网页调用时用如下代码

<asp:Image ID="Image2" runat="server" ImageUrl="pic.aspx"/>

第二种方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _111 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "image/jpeg";
        using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(50, 20))
        {

            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
            {
                Random rand = new Random();
                int code = rand.Next(1000, 9999);

                string verCode = code.ToString();

                Session["Code"] = verCode;//写一个session:Session["Code"],把随机生成的verCode ,存进去。


                g.DrawString(verCode, new System.Drawing.Font("黑体", 15), System.Drawing.Brushes.Green, 0, 0);
                bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }
}

//第三种效果(做OA时实现的)

using System;
using System.Collections;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;


public partial class ValidateCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //调用函数将验证码生成图片 
        this.CreateCheckCodeImage(GenerateCheckCode());
        //Response.Redirect("denglu.aspx");
    }




    private string GenerateCheckCode()
    {  //产生五位的随机字符串
        int number;
        char code;
        string checkCode = String.Empty;


        System.Random random = new Random();


        for (int i = 0; i < 5; i++)
        {
            number = random.Next();


            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                code = (char)('a' + (char)(number % 26));


            checkCode += code.ToString();
        }


        //Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
       //用于客户端校验码比较


        return checkCode;
    }


    private void CreateCheckCodeImage(string checkCode)
    {  //将验证码生成图片显示
        if (checkCode == null || checkCode.Trim() == String.Empty)
            return;


        Session["CheckCode"] = checkCode;
        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 18.5)), 28);
        Graphics g = Graphics.FromImage(image);


        try
        {
            //生成随机生成器 
            Random random = new Random();


            //清空图片背景色 
            g.Clear(Color.AntiqueWhite);


            //画图片的背景噪音线 
            for (int i = 0; i < 10; 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 System.Drawing.Font("Arial", 18, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);


            //画图片的前景噪音点 
            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());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }


    private string GenCode(int num)
    {
        //string str = "的一是在不123456789了Q有和人这Q中大为W上个国我以要他时来E用ASDFGHJKLIUYTREWQZXCVBNM3们生到作地R于出就分对成会可主发年动同工也能下2过子2说产43种ASDFGHJKLIUYTREWQZXCVBNM3面而方后多定行学法0所民得经十三之进着等部度sASDFGHJKLIUYTREWQZXCVBNM3家电力里如水化高自二k123456789q加量都两体制机9当使点从业1本去把性3好应开它E合R还因由其D些然前外天政ASDFGHJKLIUYTREWQZXCVBNM3W四日那社E义事平SWQ形RFE相a全h表间样与关j各重新线内数正心反8你明l看原又么z利比或T但质123456789气第4向道命W3此变43条只DF没结0S解a问A意建8月公0无7系军很情AUF者4W最立代想D1已L通G并提7g直4L34题H党123456789程展五U3果料U象员革4位入常文2总次品式活设U及AY管A特件长求w老头基资5边流2路F级S少图3山统接知5TK较S将0组3见计F别她手5角期b根0论ASDFGHJKLIUYTREWQZXCVBNM3油思s术极交受U123456789联20什认六共S权F收asdecvrrtfghujnmkiolpz证改F清D己美4再采转更7单SD风5切U8打白J2教速花带安IM场123456789身车J例真务具万每目至达G走积r,示345议声U报N斗完类0八离ASDFGHJKLIUYTREWQ123456789ZXCVBNM3华名确A才SS科张CDXG信U马节话XZ米U整空Z元Y况D今集a温传土许步pGBY群广J石记asdecvrrtfghujnmk123456789iolpz需段H4研界拉J林律叫K且究O观越H织K6装U影casdecvr123456789rtfghujnmkiolpzL算低持v音众o3书t布A复TV容儿8际商Z非验连断HJ深难近矿千周委素M技备半办V青VT5省PD列n习响B约s支般史d感I劳便团9往5酸历市克何除消构府u称太准精值号Zi率族G维XB划选标C写存候毛3亲快2效M斯Masdecvrrtfghujnmkiolpz3院C查江4型眼5王4B按格5养N易5置M派5层片U始C却专状育7厂U京asdecvrrtfghujnmkiolpz识7适属圆8包火住调m满县局7照参红细引听该铁价严";
        string str = "123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";//去掉的O容易混淆的字母
        char[] chastr = str.ToCharArray();
        // string[] source ={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#", "$", "%", "&", "@" };
        string code = "";
        Random rd = new Random();
        int i;
        for (i = 0; i < num; i++)
        {
            //code += source[rd.Next(0, source.Length)];
            code += str.Substring(rd.Next(0, str.Length), 1);


        }
        return code;
    }
}

别的网页调用时

<img src="ValidateCode.aspx" id="ValidateCodeImage" alt="" style="cursor: hand" hspace="0" align="top" />

在登录页判断时代码(一般放在最外层)

if (this.txtyzm.Text == Session["CheckCode"].ToString())//如果验证码校验通过则继续
            


 用一般处理程序写

Handler1.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web.SessionState;
namespace 验证码
{
    /// <summary>
    /// Handler1 的摘要说明
    /// </summary>
    public class Handler1 : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
           context.Response.ContentType = "image/jpeg";
            using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(50, 20))
            {

                using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                {
                    Random rand = new Random();
                    int code = rand.Next(1000, 9999);

                    string verCode = code.ToString();

                    context.Session["Code"] = verCode;//写一个session:Session["Code"],把随机生成的verCode ,存进去。


                    g.DrawString(verCode, new System.Drawing.Font("黑体", 15), System.Drawing.Brushes.Green, 0, 0);
                    bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }
        }

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

在别的网页调用

<asp:Image ID="Image1" runat="server" ImageUrl="~/Handler1.ashx"/>

NET图片加减法的验证码控件,、 this.CreateCheckCodeImage(GenerateCheckCode()); private string GenerateCheckCode() { int intFirst, intSec, intTemp; string checkCode = String.Empty; System.Random random = new Random(); intFirst = random.Next(1, 10); intSec = random.Next(1, 10); switch (random.Next(1, 3).ToString()) { case "2": if (intFirst < intSec) { intTemp = intFirst; intFirst = intSec; intSec = intTemp; } checkCode = "=" + intFirst + "-" + intSec; Session["ValidCode"] = intFirst - intSec; break; default: checkCode = "=" + intFirst + "+" + intSec; Session["ValidCode"] = intFirst + intSec; break; } //Response.Cookies.Add(new HttpCookie("ValidCode",Movie.Common.AES.EncryptAes(checkCode))); return checkCode; } #region 产生波形滤镜效果 private const double PI = 3.1415926535897932384626433832795; private const double PI2 = 6.283185307179586476925286766559; private System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase) { System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height); // 将位图背景填充为白色 System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp); graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height); graph.Dispose(); double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width; for (int i = 0; i < destBmp.Width; i++) { for (int j = 0; j < destBmp.Height; j++) { double dx = 0; dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen; dx += dPhase; double dy = Math.Sin(dx); // 取得当前点的颜色 int nOldX = 0, nOldY = 0; nOldX = bXDir ? i + (int)(dy * dMultValue) : i; nOldY = bXDir ? j : j + (int)(dy * dMultValue); System.Drawing.Color color = srcBmp.GetPixel(i, j); if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height) { destBmp.SetPixel(nOldX, nOldY, color); } } } return destBmp; } #endregion
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值