C#制作登錄驗證碼


后台代碼:

 1 public ActionResult VerificationCode()
 2         {
 3             try
 4             {
 5                 int _verificationLength = 4;//密碼長度
 6                 int _width = 100, _height = 50;
 7                 SizeF _verificationTextSize;
 8                 Random r = new Random();
 9                 Bitmap _bitmap = new Bitmap(Server.MapPath("~/Common/Texture" + (int)r.Next(0, 3) + ".jpg"), true);//此處用的圖片
10                 TextureBrush _brush = new TextureBrush(_bitmap);
11                 //獲取驗證碼
12                 string _verificationText = ValidateCode.VerificationText(_verificationLength);
13                 //存儲驗證碼
14                 Session["VerificationCode"] = _verificationText.ToUpper();
15                 Font _font = new Font("Arial", 14, FontStyle.Bold);
16                 Bitmap _image = new Bitmap(_width, _height);
17                 Graphics _g = Graphics.FromImage(_image);
18                 //清空背景色
19                 _g.Clear(Color.White);
20                 //繪制驗證碼
21                 _verificationTextSize = _g.MeasureString(_verificationText, _font);
22                 _g.DrawString(_verificationText, _font, _brush, (_width - _verificationTextSize.Width) / 2, (_height - _verificationTextSize.Height) / 2);
23                 _image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
24                 HttpContext.Response.Write(_image);
25             }
26             catch (Exception)
27             {
28 
29             }
30             return null;
31         }

前端代碼:

1 <td>
2    <img src="" class="add-on" id="vcode" title="點擊更換驗證碼" style="float:left;clear:both;line-height:12px;border-radius:4px;" />
3    <a class="span1 pull-left" style="margin-top:4px;" onclick="getValidateCode();">點擊圖片可更換驗證碼</a>
4  </td>

JS代碼:

function getValidateCode() {
            //獲取驗證碼
            $("img#vcode").attr("src", "/manager/Login/VerificationCode?" + new Date());
            $("img#vcode").click(function () {
                $(this).attr("src", "/manager/Login/VerificationCode?" + new Date());
                $("#vcode").val("");//清空驗證碼輸入框內容
            });
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM