博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
验证码生成类
阅读量:5887 次
发布时间:2019-06-19

本文共 7338 字,大约阅读时间需要 24 分钟。

生成Image的类:

生成Image的类
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Drawing;using System.Drawing.Drawing2D;using System.Drawing.Imaging;using System.Security.Cryptography;namespace WebAppToBuildImage{    ///     /// 验证码图片类    ///     public class VerifyImageEntity    {        ///         /// 要显示的文字        ///         public string Text        {            get { return this.text; }        }        ///         /// 图片        ///         public Bitmap Image        {            get { return this.image; }        }        ///         /// 宽度        ///         public int Width        {            get { return this.width; }        }        ///         /// 高度        ///         public int Height        {            get { return this.height; }        }        private string text;        private int width;        private int height;        private Bitmap image;        private static byte[] randb = new byte[4];        private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider();        ///         /// 构造函数        ///         /// 要显示的验证码        /// 宽度        /// 高度        public VerifyImageEntity(string code, int width, int height)        {            this.text = code;            this.width = width;            this.height = height;            this.GenerateImage();        }        ///         /// 析构函数        ///         ~VerifyImageEntity()        {            Dispose(false);        }        public void Dispose()        {            GC.SuppressFinalize(this);            this.Dispose(true);        }        protected virtual void Dispose(bool disposing)        {            if (disposing)                this.image.Dispose();        }        private FontFamily[] fonts = {                                new FontFamily("Times New Roman"),                                new FontFamily("Georgia"),                                new FontFamily("Arial"),                                new FontFamily("Comic Sans MS")                            };        public static int Next()        {            rand.GetBytes(randb);            int value = BitConverter.ToInt32(randb, 0);            if (value < 0) value = -value;            return value;        }        public static int Next(int max)        {            rand.GetBytes(randb);            int value = BitConverter.ToInt32(randb, 0);            value = value % (max + 1);            if (value < 0) value = -value;            return value;        }        public static int Next(int min, int max)        {            int value = Next(max - min) + min;            return value;        }        ///         /// 生成验证码图片        ///         private void GenerateImage()        {            Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);            Graphics g = Graphics.FromImage(bitmap);            Rectangle rect = new Rectangle(0, 0, this.width, this.height);            g.SmoothingMode = SmoothingMode.AntiAlias;            g.Clear(Color.White);            int emSize = Next(3) + 18;//(int)((this.width - 20) * 2 / text.Length);            FontFamily family = fonts[Next(fonts.Length - 1)];            Font font = new Font(family, emSize, FontStyle.Bold);            SizeF measured = new SizeF(0, 0);            SizeF workingSize = new SizeF(this.width, this.height);            while (emSize > 2 && (measured = g.MeasureString(text, font)).Width > workingSize.Width || measured.Height > workingSize.Height)            {                font.Dispose();                font = new Font(family, emSize -= 2);            }            SolidBrush drawBrush = new SolidBrush(Color.FromArgb(Next(100), Next(100), Next(100)));            for (int x = 0; x < 3; x++)            {                Pen linePen = new Pen(Color.FromArgb(Next(150), Next(150), Next(150)), 1);                g.DrawLine(linePen, new PointF(0.0F + Next(20), 0.0F + Next(this.height)), new PointF(0.0F + Next(this.width), 0.0F + Next(this.height)));            }            for (int x = 0; x < this.text.Length; x++)            {                drawBrush.Color = Color.FromArgb(Next(150) + 20, Next(150) + 20, Next(150) + 20);                PointF drawPoint = new PointF(0.0F + Next(4) + x * 15, 8.0F + Next(4));                g.DrawString(this.text[x].ToString(), font, drawBrush, drawPoint);            }            double distort = Next(5, 10) * (Next(10) == 1 ? 1 : -1);            using (Bitmap copy = (Bitmap)bitmap.Clone())            {                for (int y = 0; y < height; y++)                {                    for (int x = 0; x < width; x++)                    {                        int newX = (int)(x + (distort * Math.Sin(Math.PI * y / 84.0)));                        int newY = (int)(y + (distort * Math.Cos(Math.PI * x / 54.0)));                        if (newX < 0 || newX >= width) newX = 0;                        if (newY < 0 || newY >= height) newY = 0;                        bitmap.SetPixel(x, y, copy.GetPixel(newX, newY));                    }                }            }            //g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1);            font.Dispose();            drawBrush.Dispose();            g.Dispose();            this.image = bitmap;        }    }}

添加一个img.aspx页面用于显示image:

img.aspx
<%@ Page Title="主页" Language="C#" AutoEventWireup="true" ContentType="image/jpeg"    CodeBehind="img.aspx.cs" Inherits="WebAppToBuildImage._Default" %>
img.aspx.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Text;namespace WebAppToBuildImage{    public partial class _Default : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {        }        protected override void OnInit(EventArgs e)        {            base.OnInit(e);            string authStr = CreateAuthStr(4);            System.Diagnostics.Debug.WriteLine(authStr);            VerifyImageEntity verifyimg = new VerifyImageEntity(authStr, 100, 35);            System.Drawing.Bitmap image = verifyimg.Image;            System.Web.HttpContext.Current.Response.ContentType = "image/pjpeg";            //Session["AuthStr"] = authStr.ToLower();            image.Save(this.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);        }        ///         /// 产生验证码        ///         /// 
验证码
public static string CreateAuthStr(int len) { int number; StringBuilder checkCode = new StringBuilder(); Random random = new Random(); for (int i = 0; i < len; i++) { number = random.Next(); if (number % 2 == 0) { checkCode.Append((char)('0' + (char)(number % 10))); } else { checkCode.Append((char)('A' + (char)(number % 26))); } } return checkCode.ToString(); } }}

调用[看高亮那一句]:

<%@ Page Title="关于我们" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"    CodeBehind="About.aspx.cs" Inherits="WebAppToBuildImage.About" %>

关于

img

转载地址:http://wjgix.baihongyu.com/

你可能感兴趣的文章
web框架-(七)Django补充---models进阶操作及modelform操作
查看>>
kali访问宿主机Web页面解决方案
查看>>
html简介
查看>>
Android利用文本分割拼接开发一个花藤文字生成
查看>>
哈夫曼树的实现
查看>>
12-18Windows窗体应用小程序之记事本(1)
查看>>
02-18 报表
查看>>
毕业论文一次性修改所有字母和数字的字体
查看>>
结构体:HASH表模板
查看>>
[转]理解Linux文件系统之inode
查看>>
在i3 Cpu上允许64位系统
查看>>
视频编解码学习之五:差错控制及传输
查看>>
String:自动进行空间扩展
查看>>
Postman教程
查看>>
python模块--os模块
查看>>
HSSFRow获取单元格方法与区别
查看>>
《图解HTTP》读书笔记
查看>>
iOS开发-单例模式
查看>>
词汇小助手V1.2——可以显示英语单词的国际音标
查看>>
洛谷 1365 WJMZBMR打osu! / Easy
查看>>