asp.net 验证码 图片验证码

废话没有,代码(img.aspx.cs):

view sourceprint
?
01 using System;

02 using System.Data;

03 using System.Configuration;

04 using System.Collections;

05 using System.Web;

06 using System.Web.Security;

07 using System.Web.UI;

08 using System.Web.UI.WebControls;

09 using System.Web.UI.WebControls.WebParts;

10 using System.Web.UI.HtmlControls;

11 using System.Drawing;

12

13 public partial class salt_img : System.Web.UI.Page

14 {

15 protected void Page_Load(object sender, EventArgs e)

16 {

17 string checkCode = CreateRandomCode(4);

18 Session["CheckCode"] = checkCode;

19 CreateImage(checkCode);

20 }

21

22 private string CreateRandomCode(int codeCount)

23 {

24 string allChar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,R,S,T,U,W,X,Y,Z";

25 string[] allCharArray = allChar.Split(',');

26 string randomCode = "";

27 int temp = -1;

28

29 Random rand = new Random();

30 for (int i = 0; i < codeCount; i++)

31 {

32 if (temp != -1)

33 {

34 rand = new Random(i * temp * ((int)DateTime.Now.Ticks));

35 }

36 int t = rand.Next(allCharArray.Length);

37 if (temp == t)

38 {

39 return CreateRandomCode(codeCount);

40 }

41 temp = t;

42 randomCode += allCharArray[t];

43 }

44 return randomCode;

45 }

46

47 private void CreateImage(string checkCode)

48 {

49 int iwidth = (int)(checkCode.Length * 13);

50 System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);

51 Graphics g = Graphics.FromImage(image);

52 Font f = new System.Drawing.Font("Arial", 12, System.Drawing.FontStyle.Bold);

53 Brush b = new System.Drawing.SolidBrush(Color.Black);

54 //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);

55 g.Clear(Color.White);

56 g.DrawString(checkCode, f, b, 3, 3);

57

58 Pen blackPen = new Pen(Color.Black, 0);

59 Random rand = new Random();

60 for (int i = 0; i < 3; i++)//干扰线

61 {

62 int y = rand.Next(image.Height);

63 g.DrawLine(blackPen, 0, y, image.Width, y);

64 }

65

66 System.IO.MemoryStream ms = new System.IO.MemoryStream();

67 image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

68 Response.ClearContent();

69 Response.ContentType = "image/Jpeg";

70 Response.BinaryWrite(ms.ToArray());

71 g.Dispose();

72 image.Dispose();

73 }

74 }



代码:img.aspx (只留下下面的其余全部删除)

view sourceprint
?
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="img.aspx.cs" Inherits="salt_img" %>

 

posted @ 2010-11-24 13:20  x喜德盛  阅读(201)  评论(0编辑  收藏  举报