.Net 图片验证码作法(C#版)

1、建立一个CHKCode.aspx ,CHKCode.aspx.cs的代码如下:

  1. using System;
  2. using System.Drawing;
  3. using System.Drawing.Imaging;
  4. using System.IO;
  5. public partial class CHKCode : System.Web.UI.Page
  6. {
  7.     protected void Page_Load(object sender, EventArgs e)
  8.     {
  9.         ShowImg();
  10.     }
  11.     private void ShowImg()
  12.     {
  13.         Random ran = new Random();
  14.         int intRandom = ran.Next(1001, 9999);
  15.         //将随机数(验证字串)写入Session
  16.         Session.RemoveAll();
  17.         Session["CHKCode"] = intRandom;
  18.         //字体名
  19.         string strFontName = "Arial";
  20.         //字体大小
  21.         int intFontSize = 9;
  22.         //图像宽
  23.         int intWidth = 35;
  24.         //图像长
  25.         int intHeight = 18;
  26.         //背景颜色
  27.         Color bgColor = ColorTranslator.FromHtml("#" + Request.QueryString["colorb"]);
  28.         //前景颜色
  29.         Color foreColor = ColorTranslator.FromHtml("#" + Request.QueryString["colorf"]);
  30.         //产生字体
  31.         Font forFont = new Font(strFontName, intFontSize, FontStyle.Bold);
  32.         //生成图片
  33.         Bitmap newBitmap = new Bitmap(intWidth, intHeight, PixelFormat.Format32bppArgb);
  34.         Graphics g = Graphics.FromImage(newBitmap);
  35.         //定义一个四方形框与字片一样大小
  36.         Rectangle newRect = new Rectangle(0, 0, intWidth, intHeight);
  37.         //涂上背景色
  38.         g.FillRectangle(new SolidBrush(bgColor), newRect);
  39.         //写字
  40.         g.DrawString(intRandom.ToString(), forFont, new SolidBrush(foreColor), 2, 2);
  41.         MemoryStream mStream = new MemoryStream();
  42.         //存入MemoryStream
  43.         newBitmap.Save(mStream, ImageFormat.Gif);
  44.         g.Dispose();
  45.         newBitmap.Dispose();
  46.         //发送
  47.         Response.ClearContent();
  48.         Response.ContentType = "image/GIF";
  49.         Response.BinaryWrite(mStream.ToArray());
  50.         Response.End();
  51.     }
  52. }

2、调用方法

  1. <asp:Image ID="Image1" runat="server" ImageUrl="CHKCode.aspx?colorf=FF0000&colorb=EFB3FF" />


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值