.net生成随机验证码图片

/// <summary>
        /// 自定义图片验证码函数
        /// 该函数将生成一个图片验证码,并将生成的code存放于Session["VerifyCode"]变量内。
        /// </summary>
        /// <param name="codeLength">验证码长度</param>
        /// <param name="codeFontsize">字体大小</param>
        /// <value>该函数将生成一个图片验证码,并把生成的code存放于Session["VerifyCode"]变量内</value>
        public static void VerifyCode(int codeLength, int codeFontsize)
        {
            double PI = 6.283185307179586476925286766559;
            int m_ImgWidth = (int)(codeLength * (codeFontsize + 2.5)) + 8;  //图像宽度
            int m_ImgHeight = codeFontsize * 2 + 2;   //图像高度
            string[] m_Fonts = { "Arial", "Georgia" }; //随机字体
            string[] m_StrarraySource ={"2","3","4","5","6","7","8","9",
                             "A","B","C","D","E","F","G","H","J","K","M","N",
                             "P","Q","R","S","T","U","V","W","X","Y","Z",
                             "a","b","c","d","e","f","g","h","j","k","m","n",
                             "p","q","r","s","t","u","v","w","x","y","z"};    //随机字符所包含范围
            Color[] m_ColorarraySource ={Color.Maroon,Color.Red,Color.IndianRed,Color.Tomato,Color.OrangeRed,
                             Color.SaddleBrown,Color.Goldenrod,Color.Olive,Color.OliveDrab,Color.ForestGreen,
                             Color.Green,Color.SeaGreen,Color.LightSeaGreen,Color.Teal,Color.CadetBlue,
                             Color.SteelBlue,Color.DodgerBlue,Color.CornflowerBlue,Color.Blue,
                             Color.MediumSlateBlue,Color.BlueViolet,Color.DarkViolet,Color.Fuchsia,
                             Color.DeepPink,Color.Crimson};//随机字符颜色所包含范围
            string m_StrCode = "";         //用于存放生成的随机数
            Random m_StrRandom = new Random();
            for (int i = 0; i < codeLength; i++)
            {
                m_StrCode += m_StrarraySource[m_StrRandom.Next(0, m_StrarraySource.Length)]; //生成随机字符串
            }

            Bitmap m_BitmapImg = new Bitmap(m_ImgWidth, m_ImgHeight);//定义一个画板

            Graphics m_GraphicsSl = Graphics.FromImage(m_BitmapImg);//在画板上定义绘图的实例

            Rectangle m_RectangleJx = new Rectangle(0, 0, m_ImgWidth, m_ImgHeight);//定义一个矩形

            m_GraphicsSl.FillRectangle(new SolidBrush(Color.White), m_RectangleJx);//填充矩形
            //bPsl.DrawString(code, new Font("新宋体", 12), new SolidBrush(Color.Black), bPjx);//在矩形内画出字符串
            for (int i = 0; i < m_StrCode.Length; i++)
            {
                m_GraphicsSl.DrawString(m_StrCode.Substring(i, 1), new Font(m_Fonts[m_StrRandom.Next(0, m_Fonts.Length)].ToString(), codeFontsize, FontStyle.Bold), new SolidBrush(Color.FromKnownColor(m_ColorarraySource[m_StrRandom.Next(0, m_ColorarraySource.Length)].ToKnownColor())), i * (codeFontsize + 2) + 2, Convert.ToBoolean(i % 2) ? (m_ImgHeight - codeFontsize - 4) / 2 : (m_ImgHeight - codeFontsize - 4) / 4);
            }

            //生成干扰
            Random m_RandomR = new Random();

            //生成干扰线条
            Pen pen = new Pen(new SolidBrush(Color.FromKnownColor(m_ColorarraySource[m_StrRandom.Next(0, m_ColorarraySource.Length)].ToKnownColor())), 1);
            for (int i = 0; i < m_ImgHeight / 10; i++)
            {
                m_GraphicsSl.DrawLine(pen, new Point(m_RandomR.Next(0, m_ImgWidth), m_RandomR.Next(0, m_ImgHeight)), new Point(m_RandomR.Next(0, m_ImgWidth), m_RandomR.Next(0, m_ImgHeight)));
            }

            //生成干扰点
            //SolidBrush m_SolidbrushP2 = new SolidBrush(ColorTranslator.FromHtml("#f0f0f0"));//干扰点颜色
            SolidBrush m_SolidbrushP2 = new SolidBrush(Color.FromKnownColor(m_ColorarraySource[m_StrRandom.Next(0, m_ColorarraySource.Length)].ToKnownColor()));//干扰点颜色
            for (int i = 0; i < m_ImgWidth / 10; i++)
            {
                for (int j = 0; j < m_ImgHeight / 5; j++)
                {
                    m_GraphicsSl.FillEllipse(m_SolidbrushP2, m_RandomR.Next(m_ImgWidth), j, m_RandomR.Next(2), 2);//在矩形内画干扰点
                }
            }
            m_GraphicsSl.Dispose();

            //正弦曲线Wave扭曲图片
            Bitmap m_TempBmp = new Bitmap(m_ImgWidth, m_ImgHeight);

            // 将位图背景填充为白色
            Graphics m_Graph = Graphics.FromImage(m_TempBmp);
            m_Graph.FillRectangle(new SolidBrush(Color.White), 0, 0, m_ImgWidth, m_ImgHeight);
            m_Graph.Dispose();

            for (int i = 0; i < m_ImgWidth; i++)
            {
                for (int j = 0; j < m_ImgHeight; j++)
                {
                    double m_dx = (PI * (double)j) / (double)m_ImgHeight + 3;
                    double m_dy = Math.Sin(m_dx);

                    // 取得当前点的颜色
                    int m_nOldX = 0, m_nOldY = 0;
                    m_nOldX = i + (int)(m_dy * 2);
                    m_nOldY = j;

                    Color m_color = m_BitmapImg.GetPixel(i, j);
                    if (m_nOldX >= 0 && m_nOldX < m_ImgWidth && m_nOldY >= 0 && m_nOldY < m_ImgHeight)
                    {
                        m_TempBmp.SetPixel(m_nOldX, m_nOldY, m_color);
                    }
                }
            }
            m_BitmapImg = m_TempBmp;

            //生成边框
            Graphics m_GraphicsSl2 = Graphics.FromImage(m_BitmapImg);//在画板上定义绘图的实例
            m_GraphicsSl2.DrawRectangle(new Pen(Color.FromKnownColor(m_ColorarraySource[m_StrRandom.Next(0, m_ColorarraySource.Length)].ToKnownColor()), 0), 0, 0, m_ImgWidth - 1, m_ImgHeight - 1);

            //bPimg.Save(fullfilename, System.Drawing.Imaging.ImageFormat.Gif);//保存为文件

            m_BitmapImg.Save(System.Web.HttpContext.Current.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来

            //释放资源
            m_GraphicsSl.Dispose();
            m_BitmapImg.Dispose();
            //返回值  //将字符串保存到Session中,以便需要时进行验证
            System.Web.HttpContext.Current.Session["VerifyCode"] = m_StrCode;
        }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace FeiBoLaiTe.Admin
{
    public partial class Yanzhengma : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GenImg(GenCode(4));
            }
        }
        private string GenCode(int num)
        {
            string[] source ={"0","1","2","3","4","5","6","7","8","9",
                         "A","B","C","D","E","F","G","H","I","J","K","L","M","N",
                       "O","P","Q","R","S","T","U","V","W","X","Y","Z"};
            string code = "";
            Random rd = new Random();
            for (int i = 0; i < num; i++)
            {
                code += source[rd.Next(0, source.Length)];
            }
            return code;
        }

        //生成图片
        private void GenImg(string code)
        {
            Bitmap myPalette = new Bitmap(45, 16);//定义一个画板

            Graphics gh = Graphics.FromImage(myPalette);//在画板上定义绘图的实例

            Rectangle rc = new Rectangle(0, 0, 45, 16);//定义一个矩形

            gh.FillRectangle(new SolidBrush(Color.CornflowerBlue), rc);//填充矩形
            gh.DrawString(code, new Font("宋体", 13), new SolidBrush(Color.White), rc);//在矩形内画出字符串

            myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//将图片显示出来

            Session["code"] = code;//将字符串保存到Session中,以便需要时进行验证

            gh.Dispose();
            myPalette.Dispose();
        }
    }
}
private string GenerateCheckCode()
        {
            int number;
            string strCode = string.Empty;
            //随机种子
            //Random random = new Random();
            //for (int i = 0; i < 4; i++) //验证码长度为4
            //{
            //    //随机整数
            //    number = random.Next();
            //    //字符从0-9,A-Z中产生,对应的ASCII码为48-57,65-90
            //    number = number % 36;
            //    if (number < 10)
            //    {
            //        number += 48;
            //    }
            //    else
            //    {
            //        number += 55;
            //    }
            //    strCode += ((char)number).ToString();
            //}

              //产生随机字符串
            strCode =  GenCode(4);

            //将字符串保存在Cookies
            Response.Cookies.Add(new HttpCookie("gst_checkCode", strCode));
            return strCode;

        }

        private string GenCode(int num)
        {
            string[] source ={"0","1","2","3","4","5","6","7","8","9",
                                "A","B","C","D","E","F","G","H","i","J","K","L","M","N",
                                "o","P","Q","R","S","T","U","V","W","X","Y","Z"};
            string code = "";
            Random rd = new Random();
            for (int i = 0; i < num; i++)
            {
                code += source[rd.Next(0, source.Length)];
            }
            return code;
        }

        //生成图片
        private void CreateCheckCodeImage(string checkCode)
        {
            //若检验码为空,则直接返回
            if (checkCode == null || checkCode.Trim() == string.Empty)
                return;
            //根据验证码长度确定输出图片的长度
            System.Drawing.Bitmap image = new Bitmap((int)Math.Ceiling(float.Parse((checkCode.Length * 15).ToString())), 20);

            //创建Graphics对象
            System.Drawing.Graphics g = Graphics.FromImage(image);

            //生成随机数种子
            Random random = new Random();
            //清除图片背景颜色
            g.Clear(Color.White);
            //画背景图片的噪音线10条
            for (int i = 0; i < 6; i++)
            {
                //噪音线起点坐标(x1,y1),终点坐标(x2,y2)
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                //用银色线画出噪音线
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            //输出图片中校验码的字体:12号Arial,粗斜体
            Font font = new Font("Arial", 12, FontStyle.Bold);
            //线性渐变画刷
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Width), Color.Blue, Color.Purple, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);
            //画图片的前景噪点50个
            for (int i = 0; i < 50; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            //画图片段边框线
            g.DrawRectangle(new Pen(Color.SaddleBrown), 0, 0, image.Width - 1, image.Height - 1);
            //创建内存流用于输出图片
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //图片格式指定为png
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

            //清除缓冲区流中的所有输出
            Response.ClearContent();
            //输出流的Http Mime类型设置为"image/Png"
            Response.ContentType = "image/Png";
            //输出图片的二进制流
            Response.BinaryWrite(ms.ToArray()); 

            //释放Bitmap和Graphics对象
            g.Dispose();
            image.Dispose();
        }
时间: 2024-10-27 17:28:47

.net生成随机验证码图片的相关文章

struts2生成随机验证码图片

之前想做一个随机验证码的功能,自己也搜索了一下别人写的代码,然后自己重新用struts2实现了一下,现在将我自己实现代码贴出来!大家有什么意见都可以指出来! 首先是生成随机验证码图片的action: CreateImageAction: package com.xiaoluo.action; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedIm

python模块之PIL模块(生成随机验证码图片)

PIL简介 什么是PIL PIL:是Python Image Library的缩写,图像处理的模块.主要的类包括Image,ImageFont,ImageDraw,ImageFilter PIL的导入 首先需要安装一下pillow包 pip install pillow 然后就可以调用PIL里的类了 from PIL import Image from PIL import ImageFont from PIL import ImageDraw from PIL import ImageFilt

生成随机验证码图片的工具类

package utils; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.io.ByteArrayOutpu

学习python:实例2.用PIL生成随机验证码

效果: 代码: # 生成随机验证码图片 import string from random import randint, sample from PIL import Image, ImageDraw, ImageFont, ImageFilter # Image 负责处理图片 # ImageDraw 画笔 # ImageFont 文字 # ImageFileter 滤镜 # 定义变量 img_size = (150,50)        # 定义画布大小 img_rgb = (255,255

Python使用PIL模块生成随机验证码

PIL模块的安装 pip3 install pillow 生成随机验证码图片 import random from PIL import Image, ImageDraw, ImageFont from io import BytesIO def random_str(): ''' 生成随机字符 :return:随机字符 ''' random_int = str(random.randint(0,9)) random_up = chr(random.randint(65,90)) random_

java随机动态生成汉字验证码图片的实例代码分享

原创不易,转载请注明出处:java随机动态生成汉字验证码图片的实例代码分享 代码下载地址:http://www.zuidaima.com/share/1809721113234432.htm 汉字验证码实现原理 将汉字和干扰线生成图片并将汉字保存到session,前台获取每次生成验证码图片并用文本框值和session值比较,功能相对来说还是比较简单的. 效果图,如下: 验证成功后: java随机动态生成汉字验证码图片的实例代码分享

输出随机验证码图片

1 /** 2 * //输出随机验证码图片:CAPTCHA图像 3 */ 4 public class ServletDemo1 extends HttpServlet { 5 private static final long serialVersionUID = 1L; 6 7 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOEx

在JSP中动态生成随机验证码,登录时后台校验验证码,以及如何避免同一个验证码被重复提交爆破密码

只需几步就可以生成动态随机的验证码,最终效果如下图: 一 前台显示页面login.jsp 其中验证码显示的是一张图片,链接指向的是生成验证码的servlet,同时点击图片后触发changeImg()这个js函数,使其动态生成一个新的验证码,这个函数中的参数t=Math.random()并不会参与验证码的生成,它的作用仅仅只是表示每次提交的并不是同一个请求,需要单独处理,完整的login.jsp代码如下: <%@ page language="java" contentType=&

Python 生成随机验证码

Python生成随机验证码 Python生成随机验证码,需要使用PIL模块. 安装: 1 pip3 install pillow 基本使用 1. 创建图片 1 2 3 4 5 6 7 8 9 from PIL import Image img = Image.new(mode='RGB', size=(120, 30), color=(255, 255, 255)) # 在图片查看器中打开 # img.show()  # 保存在本地 with open('code.png','wb') as f