生成图片验证码

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

public partial class _Default : System.Web.UI.Page 
{
    
    
protected void Page_Load(object sender, EventArgs e)
    
{
                
//BmpWeb.MyService imgsvr = new BmpWeb.MyService();
        
//string strKey = "";
        
//byte[] data = imgsvr.GenerateVerifyImage(7, ref strKey);
        
//Response.OutputStream.Write(data, 0, data.Length);
        
        
//System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
        
//System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
        
        
//img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Bmp);

        
string strKey = "";
        
byte[] data = GenerateVerifyImage(5ref strKey);

        
//cookies
        Response.Cookies.Add(new HttpCookie("Img_CheckCode", strKey));
        Response.OutputStream.Write(data, 
0, data.Length);

    }


    
/// <summary>
    
/// 将字节流转成图片数据
    
/// </summary>
    
/// <param name="imgData"></param>
    
/// <returns></returns>

    private System.Drawing.Image convertByteToImg(byte[] imgData)
    
{
        System.IO.MemoryStream ms 
= new System.IO.MemoryStream(imgData);
        System.Drawing.Image img 
= System.Drawing.Image.FromStream(ms);
        
return img;
    }


    
/// <summary>
    
/// 生成图片验证码 可以作为web Services 调用
    
/// </summary>
    
/// <param name="nLen">验证码的长度</param>
    
/// <param name="strKey">输出参数,验证码的内容</param>
    
/// <returns>图片字节流</returns>

    public byte[] GenerateVerifyImage(int nLen, ref string strKey)
    
{
        
int nBmpWidth = 13 * nLen + 5;
        
int nBmpHeight = 25;
        System.Drawing.Bitmap bmp 
= new System.Drawing.Bitmap(nBmpWidth, nBmpHeight);

        
// 1. 生成随机背景颜色
        int nRed, nGreen, nBlue;  // 背景的三元色
        System.Random rd = new Random((int)System.DateTime.Now.Ticks);
        nRed 
= rd.Next(255% 128 + 128;
        nGreen 
= rd.Next(255% 128 + 128;
        nBlue 
= rd.Next(255% 128 + 128;

        
// 2. 填充位图背景
        System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(bmp);
        graph.FillRectangle(
new SolidBrush(System.Drawing.Color.FromArgb(nRed, nGreen, nBlue))
         , 
0
         , 
0
         , nBmpWidth
         , nBmpHeight);


        
// 3. 绘制干扰线条,采用比背景略深一些的颜色
        int nLines = 3;
        System.Drawing.Pen pen 
= new System.Drawing.Pen(System.Drawing.Color.FromArgb(nRed - 17, nGreen - 17, nBlue - 17), 2);
        
for (int a = 0; a < nLines; a++)
        
{
            
int x1 = rd.Next() % nBmpWidth;
            
int y1 = rd.Next() % nBmpHeight;
            
int x2 = rd.Next() % nBmpWidth;
            
int y2 = rd.Next() % nBmpHeight;
            graph.DrawLine(pen, x1, y1, x2, y2);
        }


        
// 采用的字符集,可以随即拓展,并可以控制字符出现的几率
        string strCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";

        
// 4. 循环取得字符,并绘制
        string strResult = "";
        
for (int i = 0; i < nLen; i++)
        
{
            
int x = (i * 13 + rd.Next(3));
            
int y = rd.Next(4+ 1;

            
// 确定字体
            System.Drawing.Font font = new System.Drawing.Font("Courier New",
             
12 + rd.Next() % 4,
             System.Drawing.FontStyle.Bold);
            
char c = strCode[rd.Next(strCode.Length)];  // 随机获取字符
            strResult += c.ToString();

            
// 绘制字符
            graph.DrawString(c.ToString(),
             font,
             
new SolidBrush(System.Drawing.Color.FromArgb(nRed - 60 + y * 3, nGreen - 60 + y * 3, nBlue - 40 + y * 3)),
             x,
             y);
        }


        
// 5. 输出字节流
        System.IO.MemoryStream bstream = new System.IO.MemoryStream();
        bmp.Save(bstream, System.Drawing.Imaging.ImageFormat.Jpeg);
        bmp.Dispose();
        graph.Dispose();

        strKey 
= strResult;
        
byte[] byteReturn = bstream.ToArray();
        bstream.Close();

        
return byteReturn;
    }

调动页面代码:
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>无标题页</title>
    
<script type="text/javascript">
        
function reloadcode()
        document.getElementById(
"imgbmp").src ="Default.aspx?" + Math.random();
        }
 
    
</script>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
        
&nbsp;<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
         
<img id="imgbmp" src="Default.aspx" alt= "看不清楚,换一个。" style="cursor : pointer;" onclick="reloadcode();" align="absmiddle" />
        
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
        
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label></div>
    
</form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Default2 : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{

    }

    
protected void Button1_Click(object sender, EventArgs e)
    
{
        
if (CheckCodeCheck())
        
{
            Label1.Text 
= "验证码相同";
        }

    }


    
public bool CheckCodeCheck()
    
{
        
if (Request.Cookies["Img_CheckCode"== null)
        
{
            Label1.Text 
= "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";
            Label1.Visible 
= true;
            
return false;
        }


        
if (String.Compare(Request.Cookies["Img_CheckCode"].Value, TextBox1.Text,false!= 0)
        
{
            Label1.Text 
= "验证码错误,请输入正确的验证码。";
            Label1.Visible 
= true;
            
return false;
        }

        
return true;
    }

}

posted @   水静痕迹  阅读(237)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示