<script type="text/javascript"> $(document).ready(function () { $("#validimg").click(function () { $("#validimg").attr('src', '@Url.Content("~/Home/GenerateImage?")' + Math.random()); }); }) </script> <div> <img alt="验证码" id="validimg" src="@Url.Action("GenerateImage", "Home")" /> </div>
public class HomeController : Controller { public byte[] Test() { Random r = new Random((int)DateTime.Now.Ticks); int startChar = 64; string result = String.Empty; for (int i = 0; i < 4; i++) { int t = r.Next(1, 27); result += Convert.ToChar(t + startChar); } var image = new Bitmap((int)Math.Ceiling(result.Length * 15.0), 22); var g = Graphics.FromImage(image); try { var random = new Random(); g.Clear(Color.White); for (int i = 0; i < 25; i++) { var x1 = random.Next(image.Width); var x2 = random.Next(image.Width); var y1 = random.Next(image.Height); var y2 = random.Next(image.Height); g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); } Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic)); var brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(result, font, brush, 3, 2); //画图片的前景干扰点 for (var i = 0; i < 100; i++) { var x = random.Next(image.Width); var 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); //保存图片数据 var stream = new MemoryStream(); image.Save(stream, ImageFormat.Jpeg); //输出图片流 return stream.ToArray(); } finally { g.Dispose(); image.Dispose(); } } // // GET: /Home/ public ActionResult Index() { return View(); } public ActionResult GenerateImage() { return File(Test(), @"image/gif"); } }