时间:2021-07-01 10:21:17 帮助过:52人阅读
- <br>using System; <br>using System.Collections.Generic; <br>using System.Linq; <br>using System.Web; <br>using System.Web.UI; <br>using System.Web.UI.WebControls; <br>using System.Drawing; <br>namespace 学生在线考试系统 <br>{ <br>public partial class AjaxAutoCode : System.Web.UI.Page <br>{ <br>//验证数字 <br>public string authcode = string.Empty; <br>protected void Page_Load(object sender, EventArgs e) <br>{ <br>#region 第一种产生验证码的方法 <br>Random random = new Random(); <br>authcode = random.Next(1111, 9999).ToString(); <br>//构造图片 <br>Bitmap image = new Bitmap(authcode.Length * 12, 25); <br>//创建画布 <br>Graphics g = Graphics.FromImage(image); <br>try <br>{ <br>g.Clear(Color.White); <br>for (int i = 0; i < 25; i++) <br>{ <br>int x1 = random.Next(image.Width); <br>int x2 = random.Next(image.Width); <br>int y1 = random.Next(image.Height); <br>int y2 = random.Next(image.Height); <br>//链接两点的线条 <br>g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); <br>} <br>Font font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Italic); <br>System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush( <br>new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkBlue, 1.2f, true); <br>g.DrawString(authcode, font, brush, 2, 2); <br>//画图片的前景噪点 <br>for (int i = 0; i < 100; i++) <br>{ <br>int x = random.Next(image.Width); <br>int y = random.Next(image.Height); <br>image.SetPixel(x, y, Color.FromArgb(random.Next())); <br>} <br>g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); <br>System.IO.MemoryStream ms = new System.IO.MemoryStream(); <br>image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); <br>ms.WriteTo(this.Response.OutputStream); <br>ms.Close(); <br>this.Response.ContentType = "image/gif"; <br>} <br>finally <br>{ <br>image.Dispose(); <br>g.Dispose(); <br>} <br>#endregion <br>} <br>} <br>} <br> <br>2、其次在显示验证码的页面定义一个JS函数 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>function fGetCode() <br>{ <br>document.getElementById("getcode").src="Default2.aspx?"+Math.random(); <br>} <br> <br>3.再编辑前台页面aspx,下面是前台页面的代码片段 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br><label>验证码</label> <br><asp:TextBox ID="txt_checkCode" runat="server" Width="178px"></asp:TextBox> <br><img src="Default2.aspx" alt="看不清楚?" id="getcode"/> <a href="javascript:fGetCode()">更换验证码</a> <br></li><li> </li><li> </li></ol></pre></li></ol></pre>