• 数字验证码的实现


    public partial class ValidateCode : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string validateCode = CreateValidateCode();   //生成验证码
            Bitmap bitmap = new Bitmap(imgWidth, imgHeight);   //生成BITMAP图像
            DisturbBitmap(bitmap);   //图像背景
            DrawValidateCode(bitmap, validateCode);  //绘制验证码图像
            bitmap.Save(Response.OutputStream, ImageFormat.Gif);  //保存验证码图像,等待输出
        }
        //定义变量
        private int codeLen = 4;     //验证码长度
        private int fineness = 85;   //图片清晰度
        private int imgWidth = 58;
        private int imgHeight = 24;
        private string fontFamily = "Times New Roman"; //字体名称
        private int fontSize = 14;
        //private int fontStyle = 0;   //字体样式
        private int posX = 0;        //绘制起始坐标X
        private int posY = 0;        //绘制起始坐标Y

        //随机生成一个验证码的值
        private string CreateValidateCode()
        {
            string validateCode = "";
            Random random = new Random();
            for (int i = 0; i < codeLen; i++)
            {
                int n = random.Next(10);
                validateCode += n.ToString();
            }
            Session["vcode"] = validateCode;
            return validateCode;
        }

        //生成麻点背景效果
        private void DisturbBitmap(Bitmap bitmap)
        {
            Random random = new Random();
            for (int i = 0; i < bitmap.Width; i++)
            {
                for (int j = 0; j < bitmap.Height; j++)
                {
                    if (random.Next(90) <= this.fineness)
                    {
                        bitmap.SetPixel(i, j, Color.LightGray);
                    }
                }
            }
        }

        //将验证码绘制到背景图像上
        private void DrawValidateCode(Bitmap bitmap, string validateCode)
        {
            Graphics g = Graphics.FromImage(bitmap); //获取绘制器对象
            Font font = new Font(fontFamily, fontSize, FontStyle.Bold); //设置绘制字体、
            g.DrawString(validateCode, font, Brushes.Black, posX, posY); //绘制验证码图像
        }
    }

  • 相关阅读:
    [NOIP 2012] 疫情控制
    [HDU 6315] Naive Operations
    [BZOJ 3363] Cow Marathon
    单片机的模块化编程
    QT中定时器的使用方法
    47: error: undefined reference to `QWebView::QWebView(QWidget*)'
    如何分析一个QT类
    个人收集的一些库、工具、技术介绍
    点阵字体显示系列之二:汉字显示
    点阵字体显示系列之一:ASCII码字库的显示
  • 原文地址:https://www.cnblogs.com/bobo41/p/3096489.html
Copyright © 2020-2023  润新知