发布一个很COOL的图片验证码程序[含源码]
一、先看看效果:
制作步骤:
(1)准备你想要的多张图片(数量不限,由你自己决定),将它们放在一个统一的目录下,比如我这里是“ValidateCodeImg”。图片尺寸尽量适合你的验证码尺寸。这样有利于达到最佳性能比。
(2)将以下代码分别COPY到你的工程目录下(记得放在ValidateCodeImg目录的上一级目录中)。
二、相关代码:
1、// ValidateCode.aspx页面:
-----------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ValidateCode.aspx.cs" Inherits="Comm_ValidateCode" %>
<!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>
</div>
</form>
</body>
</html>
2、// ValidateCode.aspx.cs
--------------------------------------
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;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
public partial class Comm_ValidateCode : System.Web.UI.Page
{
int _width = 75;
int _height = 21;
// int _width = 128;
// int _height = 40;
string imgDir = @"ValidateCodeImg";
public int Width
{
get
{
return _width;
}
set
{
_width = value;
}
}
public int Height
{
get
{
return _height;
}
set
{
_height = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["w"] != null)
{
try
{
this._width = int.Parse(Request.QueryString["w"].Trim());
}
catch (Exception exc)
{
//
}
}
if (Request.QueryString["h"] != null)
{
try
{
this._height = int.Parse(Request.QueryString["h"].Trim());
}
catch (Exception exc)
{
//
}
}
// 4位数字的验证码
if (!IsPostBack)
{
string str_ValidateCode = GetRandomNumberString(4);
//用于验证的Session
Session["ValidateCode"] = str_ValidateCode;
CreateImage(str_ValidateCode);
}
}
// 生成随机数字字符串
public string GetRandomNumberString(int int_NumberLength)
{
string str_Number = string.Empty;
Random theRandomNumber = new Random();
for (int int_index = 0; int_index < int_NumberLength; int_index++)
str_Number += theRandomNumber.Next(10).ToString();
return str_Number;
}
//生成随机颜色
public Color GetRandomColor()
{
Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
System.Threading.Thread.Sleep(RandomNum_First.Next(50));
Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);
int int_Red = RandomNum_First.Next(256);
int int_Green = RandomNum_Sencond.Next(256);
int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
int_Blue = (int_Blue > 255) ? 255 : int_Blue;
return Color.FromArgb(int_Red, int_Green, int_Blue);
}
public FileInfo[] GetAllFilesInPath(string path)
{
System.IO.DirectoryInfo di = new DirectoryInfo(path);
return di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
}
public string GetRandomFile(string path)
{
FileInfo[] fi = this.GetAllFilesInPath(path);
Random rand = new Random(new Guid().GetHashCode() + (int)DateTime.Now.Ticks);
int k = rand.Next(0, fi.Length);
return fi[k].FullName;
}
public int GetRandomAngle()
{
Random rand = new Random((int)DateTime.Now.Ticks);
System.Threading.Thread.Sleep(rand.Next(50));
return rand.Next(-45, 45);
}
//根据验证字符串生成最终图象
public void CreateImage(string str_ValidateCode)
{
//int int_ImageWidth = str_ValidateCode.Length * 13;
//int width = int_ImageWidth;
int int_ImageWidth = this.Width;
int width = int_ImageWidth;
int height = this.Height;
string filePath = Server.MapPath(imgDir);
Bitmap bgImg = (Bitmap)Bitmap.FromFile(GetRandomFile(filePath));
Random newRandom = new Random();
// 图高20px
Bitmap theBitmap = new Bitmap(width, height);
Graphics theGraphics = Graphics.FromImage(theBitmap);
theGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
theGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
theGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
theGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
// 白色背景
//theGraphics.Clear(Color.White);
theGraphics.DrawImage(bgImg, new Rectangle(0, 0, width, height), new Rectangle(0, 0, bgImg.Width, bgImg.Height), GraphicsUnit.Pixel);
// 灰色边框
theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, height - 1);
//13pt的字体
float fontSize = this.Height * 1.0f / 1.38f;
float fontSpace = fontSize / 7f;
Font theFont = new Font("Arial", fontSize);
System.Drawing.Drawing2D.GraphicsPath gp = null;
System.Drawing.Drawing2D.Matrix matrix;
for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
{
string str_char = str_ValidateCode.Substring(int_index, 1);
Brush newBrush = new SolidBrush(GetRandomColor());
Point thePos = new Point((int)(int_index * (fontSize + fontSpace) + newRandom.Next(3)), 1 + newRandom.Next(3));
gp = new System.Drawing.Drawing2D.GraphicsPath();
gp.AddString(str_char, theFont.FontFamily, 0, fontSize, thePos, new StringFormat());
matrix = new System.Drawing.Drawing2D.Matrix();
int angle = GetRandomAngle();
PointF centerPoint = new PointF(thePos.X + fontSize / 2, thePos.Y + fontSize / 2);
matrix.RotateAt(angle, centerPoint);
theGraphics.Transform = matrix;
theGraphics.DrawPath(new Pen(Color.White, 2f), gp);
//theGraphics.FillPath(new SolidBrush(Color.Black), gp);
theGraphics.FillPath(new SolidBrush(GetRandomColor()), gp);
theGraphics.ResetTransform();
}
if (gp != null) gp.Dispose();
// 将生成的图片发回客户端
MemoryStream ms = new MemoryStream();
theBitmap.Save(ms, ImageFormat.Png);
Response.ClearContent(); //需要输出图象信息 要修改HTTP头
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
theGraphics.Dispose();
theBitmap.Dispose();
Response.End();
}
}
三、如何使用?
1、引用验证码图形时:
<img src="ValidateCode.aspx?w=100&h=32" id="ValidateCodeAuto" width="100" height="32" align="absmiddle" /> <a href="#" οnclick="Javascript:var now=new Date();var number = now.getSeconds(); document.getElementById('ValidateCodeAuto').src='ValidateCode.aspx?w=100&h=32&dd=' + number;">看不清楚</a>
2、验证时,判断用户输入验证码是否等于 Session["ValidateCode"] 即可。
3、其他说明:(1)上面有两个参数w和h,是用来定义图形验证码大小的。比如你想将你验证码设置为128*40时,你只需要ValidateCode.aspx?w=128&h=40,然后将图片引用后面的Width,Height改成:width="128" height="40" 即可。对应的,看不清楚的Javascript代码也需要将src='ValidateCode.aspx?w=100&h=32改成:src='ValidateCode.aspx?w=128&h=40。
(2)“看不清楚”处还有一个参数dd,是用来做生成随机值以便更新验证码图片的。
转载于:https://www.cnblogs.com/yamajia/archive/2007/11/13/958205.html
发布一个很COOL的图片验证码程序[含源码]相关推荐
- java me手机版,一个经典的 JAVA ME 手机程序入门级源码
一个经典的 JAVA ME 手机程序入门级源码 一个由 Carol Hamer 写的比较有代表性的源码,作者全力推荐,尤其是对于没有 J2ME 开发经验的朋友.自己动手敲出以下贴出的 Hello.ja ...
- Qt creator5.7 OpenCV249之图片灰度处理(含源码下载)
我们先来看程序运行: 先了解下原理: 图像灰度化是指将彩色图片处理为256级的灰度图像. 公式为Gray=x*R+y*G+z*B Gray是当前像素的灰度值,x,y,z 是系数,R,G,B表示红绿蓝 ...
- 备忘录小程序(含源码)【推荐】
简单介绍一下云笔记微信小程序的功能: 以上笔记页面可以预览自己创建的所有云笔记,云笔记是创建在自己的云数据库中. 点击笔记进入,可以预览当前笔记的详细内容,同时可以通过下方功能键,修改.删除.保存操作 ...
- Qt5串口多功能助手32位版本相关程序含源码
开发平台:Qt 5.9 编译环境:MinGW 5.3 32bit Qt6.3-64位版本文章链接:(102条消息) Qt6串口多功能助手64位版本上位机源码_阿衰0110的博客-CSDN博客 免费安 ...
- 很棒的图片浏览器代码,源码研究
重要声明: 文章为原创,代码从网上扒下来,进行整合和Bug修复运用到自己的项目中或仿用户量超大的应用,比如微信.来往.美丽说.淘宝.豆瓣等等. 1. 引入了著名的Universalimageloade ...
- 一个简单的手机蓝牙聊天程序的源码
1.BlueToothMIDlet类 import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public cla ...
- python 生成exe 图片资源_爱豆图片下载(含源码及打包exe可执行文件)
import requests from lxml import etree import os # etree解析网页并返回 def parse(url): headers = { 'User-Ag ...
- RTX的LDAP验证程序(含源码)
修正服务器重启后服务无法启动成功的问题: 添加了服务依赖,服务会在rtx的主服务启动后再启动,并且当注册应用和启动应用失败时每隔30自动重试(系统应用日志可以看到重试记录),重试10次仍未成功,则退出 ...
- 用HTML和CSS做一个携程旅游手机端布局含源码分享
效果如下图所示: 文件夹内容如下: 源码分享:https://pan.baidu.com/s/1Rdt24sPEB9Rp8tnc9Udr3Q 提取码:3eka html: <!DOCTYPE ...
最新文章
- MVC中获取模型属性的Range和StringLength验证特性设置
- 03-Windows Server 2016 IIS的安装与配置
- 一个关于clear()、吸收缓存区的帖子引发的思考
- SyntaxError: Non-UTF-8 code starting with '\xba' in file 错误的解决方法!!
- 中兴没有云服务器_中国移动携手中兴通讯推进5G网络云建设
- 剑指offer51 构建乘积数组(图解)
- android友盟注意事项
- 使用节点或Express返回JSON的正确方法
- 洛谷 P2578 [ZJOI2005]九数码游戏【bfs+康托展开】
- 【LeetCode】【字符串】题号:*165. 比较版本号
- codis实现redis分片和在线扩展
- qt信号槽踩坑日记(信号执行一次,槽函数执行多次解决方案)
- 【CarMaker学习笔记】与Simulink联合仿真
- 一百行代码自制局域网双端快速传输文件系统
- AVATR阿维塔11维修手册电路图技术资料
- echarts 世界地图标点_echarts中国地图3D各个城市标点demo
- 新手操作低客单价时常见的误区有哪些?
- QT用QWidget做的气泡聊天功能,可发图片、文件、文本等气泡信息,功能简单,适合初学者
- VBS 请求WebAPI接口_C#进阶系列——WebApi 路由机制剖析:你准备好了吗?
- 实现支持 MJPEG 的播放器