新建一個.cs文件用來寫生成圖形驗證碼的方法,返回一個MemoryStream的參數。在Default.aspx中接收輸出就可以了。1.下麵是.cs的代碼using System;using System.Collections.Generic;using System.Linq;using Sys...
新建一個.cs文件用來寫生成圖形驗證碼的方法,返回一個MemoryStream的參數。在Default.aspx中接收輸出就可以了。
1.下麵是.cs的代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; /// <summary> ///BitmapImage 的摘要說明 /// </summary> public class BitmapImage { public static MemoryStream ImageCheck() { Random random = new Random(); //隨機產生4位隨機數 string checkCode = random.Next(1000, 9999).ToString(); //Bitmap是用來指定初始化時文本的大小 Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 20.5)), 22); Graphics g = Graphics.FromImage(image); try { g.Clear(Color.White);//清空圖片背景色 //畫圖片的背景噪音線這裡是4條線 for (int i = 0; i < 4; 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.Black), x1, x2, y1, y2); } Font font = new Font("Arial", 12, FontStyle.Bold); //設置顏色,起始位置等參數 LinearGradientBrush brush = new 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); MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Gif); return ms; } finally { g.Dispose(); image.Dispose(); } } }
2.以下是Default.aspx.cs中的代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { MemoryStream ms= BitmapImage.ImageCheck(); Response.ClearContent(); Response.ContentType = "image/Gif"; Response.BinaryWrite(ms.ToArray()); } }
3.截圖