登陆、注册以及用到验证码的都在这里啦!!!
我想大家在申请邮箱或者什么需要注册的地方,就算是大家最熟悉的空间都会出现验证码,那么验证码是什么呢?大家来这里就对咯……
其实验证码呢,就是一个完整的网页,这个网页里面只有大家看到的那个验证码的图片;那又是怎么实现的呢?就在这里啦 !
就像画画,最基本的是一张画布,刷子,画笔等等……很简单,来看一看咯……
View Code
1 //注意:源代码端只需要第一行 2 3 using System; 4 using System.Collections.Generic; 5 using System.Linq; 6 using System.Web; 7 using System.Web.UI; 8 using System.Web.UI.WebControls; 9 using System.Drawing; 10 using System.Drawing.Imaging; 11 using System.IO; 12 13 namespace TwoStore.UI.login 14 { 15 public partial class CodeImage : System.Web.UI.Page 16 { 17 protected void Page_Load(object sender, EventArgs e) 18 { 19 DrapingCodes(ValidateCode()); 20 } 21 private string ValidateCode() 22 { 23 string result = ""; 24 string[] codes = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "a", "b", "c", "d", "e", "f", 25 "g", "h", "i", "j", "k","l", "m", "n", "o", "p","q", "r", "s", "t", "u", "v", 26 "w", "x", "y", "z"}; 27 //创建随机数 28 Random rand = new Random(); 29 //rand.Next(codes.Length),随机数的长度为数组的长度 30 for (int i = 0; i < 4; i++) 31 { 32 result += codes[rand.Next(codes.Length)]; 33 } 34 //可以把说的值放在Session中,以判断用户输入的是否显示的验证码 35 //也可用Cookie 36 Session["code"] = result; 37 return result; 38 } 39 //画图需要导入命名空间System.Drawing;System.Drawing.Imaging;System.IO; 40 private void DrapingCodes(string code) 41 { 42 //创建画板---Bitmap---此函数重载12次 43 //创建画板时直接规定了它的width,height 44 Bitmap bmap = new Bitmap(70, 30); 45 //创建画家---并把画布给画家 46 Graphics grap = Graphics.FromImage(bmap); 47 //让画家把画板图上背景颜色 48 grap.Clear(Color.White); 49 //创建刷子 50 Brush brush = new SolidBrush(Color.Black); 51 //创建字体 52 Font f = new Font("Comic Sans MS", 15); 53 54 //开始绘画 55 grap.DrawString(code, f, brush, 10, 2); 56 57 //随机数 58 Random rand = new Random(); 59 //打上噪点 60 for (int i = 0; i < 50; i++) 61 { 62 bmap.SetPixel(rand.Next(70), rand.Next(30), Color.Black); 63 } 64 //画笔刷子 65 Brush b1 = new SolidBrush(Color.Blue); 66 //画笔 67 Pen p = new Pen(b1); 68 //7,画上几条线 69 for (int i = 0; i < 3; i++) 70 { 71 grap.DrawLine(p, rand.Next(70), rand.Next(30), rand.Next(70), rand.Next(30)); 72 } 73 //定义一个内存流 74 MemoryStream ms = new MemoryStream(); 75 //把图片放到内存流中 76 bmap.Save(ms, ImageFormat.Gif); 77 //清空输出流 78 Response.Clear(); 79 //设置输出内容的格式 80 Response.ContentType = "image/gif"; 81 //以二进制输出byte[] 82 Response.BinaryWrite(ms.ToArray()); 83 Response.End(); 84 } 85 } 86 }