先看代碼 這是產生驗證碼的。。
CreateCode.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace WebApplication1
{
public partial class CreateCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Session["CheckCode"]=CreateCheckCodeImage();
}
private string CreateCheckCodeString()
{
char[] allCharArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z' };//定義驗證字串
string randomcode = "";
Random rand = new Random();
for (int i = 0; i < 4; i++)
{
randomcode += allCharArray[rand.Next(allCharArray.Length)];
}//產生四位驗證碼
return randomcode;
}
/// <summary>
/// CreateCheckCodeImage(string sFilePath)建立驗證碼圖片;
/// </summary>
/// <param name="sFilePath"></param>
public string CreateCheckCodeImage()
{
string checkcode = CreateCheckCodeString();//擷取四位驗證碼
int iWidth = 55;//定義圖片的寬度
int iHeight = 22;//定義圖片的高度
Font font = new Font("Arial", 12, FontStyle.Bold);//定義大小為12pt的字型,用於繪製文字
SolidBrush brush = new SolidBrush(Color.Black);//定義黑色單筆畫刷
Pen pen1 = new Pen(Color.Gray, 0);//定義畫筆,用於繪製幹擾線,橫向幹擾線
Pen pen2 = new Pen(Color.FromArgb(255, 100, 100, 100), 0);//縱向幹擾線
Bitmap image = new Bitmap(iWidth, iHeight);//建立一個位元影像對象
Graphics g = Graphics.FromImage(image);//建立一個畫圖表面
g.Clear(ColorTranslator.FromHtml("#F0F0F0"));//在繪圖表面填充顏色
RectangleF rect = new RectangleF(5, 2, iWidth, iHeight);//繪製文字的矩形地區
Random rand = new Random();//產生兩條橫向幹擾線
for (int i = 0; i < 2; i++)
{
Point p1 = new Point(0, rand.Next(iHeight));
Point p2 = new Point(iWidth, rand.Next(iWidth));
g.DrawLine(pen1, p1, p2);
}
for (int i = 0; i < 4; i++)//產生四條縱向幹擾線
{
Point p1 = new Point(rand.Next(iWidth), 0);
Point p2 = new Point(rand.Next(iWidth), iHeight);
g.DrawLine(pen2, p1, p2);
}
g.DrawString(checkcode, font, brush, rect);//繪製驗證碼文字
image.Save(Response.OutputStream, ImageFormat.Jpeg);//儲存驗證映像於輸出資料流
Response.ContentType = "image/Jpeg";
g.Dispose();
image.Dispose();
return checkcode;//返回驗證碼,用於校正
}
}
}
--------------------------------------
下面我們看前台如何?點擊重新整理
這裡用的是html的控制項。。。
<script type="text/javascript">
function refreshimg()
{
var verify= document.getElementById("img"); //img為下面html控制項的id
verify.setAttribute('src','CreateCode.aspx?'+Math.random());
}
</script>
<style type="text/css">
</style>
<img id="img" src="CreateCode.aspx " alt="驗證碼"style="cursor: pointer;" onclick="this.src=this.src+'?'"><a href="javascript:refreshimg()" >看不清楚換一張</a> <br /><!--點擊文本更換驗證碼-->
--------------------------
個人css一知半解。做的比較醜。這個點擊圖片可以更換,點擊超連結也可以。其實重要的是javascript那個地方怎麼寫。。看來js還得好好學學。。之前喵了點。。。