中文彩色验证码实现(变形/噪点/点击更换

                 1using System;
  2using System.Data;
  3using System.Configuration;
  4using System.Web;
  5using System.Web.Security;
  6using System.Web.UI;
  7using System.Web.UI.WebControls;
  8using System.Web.UI.WebControls.WebParts;
  9using System.Web.UI.HtmlControls;
 10using System.Drawing;
 11using System.Text;
 12
 13/** <summary>
 14/// VryImgGen 的摘要说明
 15/// </summary>
 16public class VryImgGen
 17...{
 18    public static string ChineseChars = String.Empty;
 19
 20    /** <summary>
 21    /// 英文与数字串
 22    /// </summary>
 23    protected static readonly string EnglishOrNumChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
 24
 25    public VryImgGen()
 26    ...{
 27        rnd = new Random(unchecked((int)DateTime.Now.Ticks));
 28    }
 29//该源码下载自 www.51aspx.com(51aspx.com)
 30
 31    /** <summary>
 32    /// 全局随机数生成器
 33    /// </summary>
 34    private Random rnd;
 35
 36    int length = 5;
 37    /** <summary>
 38    /// 验证码长度(默认6个验证码的长度)
 39    /// </summary>
 40    public int Length
 41    ...{
 42        get ...{ return length; }
 43        set ...{ length = value; }
 44    }
 45
 46    int fontSize = 18;
 47    /** <summary>
 48    /// 验证码字体大小(为了显示扭曲效果,默认30像素,可以自行修改)
 49    /// </summary>
 50    public int FontSize
 51    ...{
 52        get ...{ return fontSize; }
 53        set ...{ fontSize = value; }
 54    }
 55
 56    int padding = 4;
 57    /** <summary>
 58    /// 边框补(默认4像素)
 59    /// </summary>
 60    public int Padding
 61    ...{
 62        get ...{ return padding; }
 63        set ...{ padding = value; }
 64    }
 65
 66    bool chaos = true;
 67    /** <summary>
 68    /// 是否输出燥点(默认输出)
 69    /// </summary>
 70    public bool Chaos
 71    ...{
 72        get ...{ return chaos; }
 73        set ...{ chaos = value; }
 74    }
 75
 76    Color chaosColor = Color.LightGray;
 77    /** <summary>
 78    /// 输出燥点的颜色(默认灰色)
 79    /// </summary>
 80    public Color ChaosColor
 81    ...{
 82        get ...{ return chaosColor; }
 83        set ...{ chaosColor = value; }
 84    }
 85
 86    Color backgroundColor = Color.White;
 87    /** <summary>
 88    /// 自定义背景色(默认白色)
 89    /// </summary>
 90    public Color BackgroundColor
 91    ...{
 92        get ...{ return backgroundColor; }
 93        set ...{ backgroundColor = value; }
 94    }
 95
 96    Color[] colors = ...{ Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
 97    /** <summary>
 98    /// 自定义随机颜色数组
 99    /// </summary>
100    public Color[] Colors
101    ...{
102        get ...{ return colors; }
103        set ...{ colors = value; }
104    }
105
106    string[] fonts = ...{ "Arial", "Georgia" };
107    /** <summary>
108    /// 自定义字体数组
109    /// </summary>
110    public string[] Fonts
111    ...{
112        get ...{ return fonts; }
113        set ...{ fonts = value; }
114    }
115
116    产生波形滤镜效果#region 产生波形滤镜效果
117
118    private const double PI = 3.1415926535897932384626433832795;
119    private const double PI2 = 6.283185307179586476925286766559;
120
121    /** <summary>
122    /// 正弦曲线Wave扭曲图片(Edit By 51aspx.com)
123    /// </summary>
124    /// <param name="srcBmp">图片路径</param>
125    /// <param name="bXDir">如果扭曲则选择为True</param>
126    /// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
127    /// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
128    /// <returns></returns>
129    public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
130    ...{
131        System.Drawing.Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height);
132
133        // 将位图背景填充为白色
134        System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
135        graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
136        graph.Dispose();
137
138        double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;
139
140        for (int i = 0; i < destBmp.Width; i++)
141        ...{
142            for (int j = 0; j < destBmp.Height; j++)
143            ...{
144                double dx = 0;
145                dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
146                dx += dPhase;
147                double dy = Math.Sin(dx);
148
149                // 取得当前点的颜色
150                int nOldX = 0, nOldY = 0;
151                nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
152                nOldY = bXDir ? j : j + (int)(dy * dMultValue);
153
154                System.Drawing.Color color = srcBmp.GetPixel(i, j);
155                if (nOldX >= 0 && nOldX < destBmp.Width
156                 && nOldY >= 0 && nOldY < destBmp.Height)
157                ...{
158                    destBmp.SetPixel(nOldX, nOldY, color);
159                }
160            }
161        }
162
163        return destBmp;
164    }
165
166
167
168    #endregion
169
170    /** <summary>
171    /// 生成校验码图片
172    /// </summary>
173    /// <param name="code">验证码</param>
174    /// <returns></returns>
175    public Bitmap CreateImage(string code)
176    ...{
177        int fSize = FontSize;
178        int fWidth = fSize + Padding;
179
180        int imageWidth = (int)(code.Length * fWidth) + 4 + Padding * 2;
181        int imageHeight = fSize * 2 + Padding * 2;
182
183        System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);
184
185        Graphics g = Graphics.FromImage(image);
186
187        g.Clear(BackgroundColor);
188
189        //给背景添加随机生成的燥点
190        if (this.Chaos)
191        ...{
192
193            Pen pen = new Pen(ChaosColor, 0);
194            int c = Length * 10;
195
196            for (int i = 0; i < c; i++)
197            ...{
198                int x = rnd.Next(image.Width);
199                int y = rnd.Next(image.Height);
200
201                g.DrawRectangle(pen, x, y, 1, 1);
202            }
203        }
204
205        int left = 0, top = 0, top1 = 1, top2 = 1;
206
207        int n1 = (imageHeight - FontSize - Padding * 2);
208        int n2 = n1 / 4;
209        top1 = n2;
210        top2 = n2 * 2;
211
212        Font f;
213        Brush b;
214
215        int cindex, findex;
216
217        //随机字体和颜色的验证码字符
218        for (int i = 0; i < code.Length; i++)
219        ...{
220            cindex = rnd.Next(Colors.Length - 1);
221            findex = rnd.Next(Fonts.Length - 1);
222
223            f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
224            b = new System.Drawing.SolidBrush(Colors[cindex]);
225
226            if (i % 2 == 1)
227            ...{
228                top = top2;
229            }
230            else
231            ...{
232                top = top1;
233            }
234
235            left = i * fWidth;
236
237            g.DrawString(code.Substring(i, 1), f, b, left, top);
238        }
239
240        //画一个边框 边框颜色为Color.Gainsboro
241        g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
242        g.Dispose();
243
244        //产生波形(Add By 51aspx.com)
245        image = TwistImage(image, true, 8, 4);
246
247        return image;
248    }
249
250    /** <summary>
251    /// 生成随机字符码
252    /// </summary>
253    /// <param name="codeLen">字符串长度</param>
254    /// <param name="zhCharsCount">中文字符数</param>
255    /// <returns></returns>
256    public string CreateVerifyCode(int codeLen, int zhCharsCount)
257    ...{
258        char[] chs = new char[codeLen];
259
260        int index;
261        for (int i = 0; i < zhCharsCount; i++)
262        ...{
263            index = rnd.Next(0, codeLen);
264            if (chs[index] == '/0')
265                chs[index] = CreateZhChar();
266            else
267                --i;
268        }
269        for (int i = 0; i < codeLen; i++)
270        ...{
271            if (chs[i] == '/0')
272                chs[i] = CreateEnOrNumChar();
273        }
274
275        return new string(chs, 0, chs.Length);
276    }
277
278    /** <summary>
279    /// 生成默认长度5的随机字符码
280    /// </summary>
281    /// <returns></returns>
282    public string CreateVerifyCode()
283    ...{
284        return CreateVerifyCode(Length, 0);
285    }
286
287    /** <summary>
288    /// 生成英文或数字字符
289    /// </summary>
290    /// <returns></returns>
291    protected char CreateEnOrNumChar()
292    ...{
293        return EnglishOrNumChars[rnd.Next(0, EnglishOrNumChars.Length)];
294    }
295
296    /** <summary>
297    /// 生成汉字字符
298    /// </summary>
299    /// <returns></returns>
300    protected char CreateZhChar()
301    ...{
302        //若提供了汉字集,查询汉字集选取汉字
303        if (ChineseChars.Length > 0)
304        ...{
305            return ChineseChars[rnd.Next(0, ChineseChars.Length)];
306        }
307        //若没有提供汉字集,则根据《GB2312简体中文编码表》编码规则构造汉字
308        else
309        ...{
310            byte[] bytes = new byte[2];
311
312            //第一个字节值在0xb0, 0xf7之间
313            bytes[0] = (byte)rnd.Next(0xb0, 0xf8);
314            //第二个字节值在0xa1, 0xfe之间
315            bytes[1] = (byte)rnd.Next(0xa1, 0xff);
316
317            //根据汉字编码的字节数组解码出中文汉字
318            string str1 = Encoding.GetEncoding("gb2312").GetString(bytes);
319
320            return str1[0];
321        }
322    }
323
324}
325
   
随机生成6位图片验证码. /// <summary> /// PicHandler1 的摘要说明 /// </summary> public class PicHandler1 : IHttpHandler, IRequiresSessionState { private string mCheckNo = string.Empty; protected ImgBuilder _ImgBuilder = new ImgBuilder(); protected VryImgGen _ImgBuilderNew = new VryImgGen(); private string _text = string.Empty; private string _font = "宋体"; private int _fontSize = 8; private int _padding = 2; public void ProcessRequest(HttpContext context) { mCheckNo = DisCheckNo(); context.Session["CheckCode"] = mCheckNo; this._ImgBuilder.FontSize = this._fontSize; this._ImgBuilder.Padding = this._padding; if (!string.IsNullOrEmpty(this._font)) { this._ImgBuilder.Fonts = new string[] { this._font }; } this._ImgBuilderNew.ChaosWight = 40; this._ImgBuilderNew.FontSize = 25; this._ImgBuilderNew.Padding = 3; System.Drawing.Bitmap image = this._ImgBuilderNew.CreateImage(mCheckNo); System.IO.MemoryStream ms = new System.IO.MemoryStream(); image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); context.Response.ClearContent(); context.Response.ContentType = "image/Jpeg"; context.Response.BinaryWrite(ms.ToArray()); context.Session["CheckCode"] = mCheckNo.ToString(); //如果没有实现IRequiresSessionState,则这里会出错,也无法生成图片 context.Response.End(); } //验证码生成 protected string DisCheckNo() { string hash = HashCode.GetNext(); string CheckNo = string.Empty; Random rd = new Random(DateTime.Now.Millisecond); for (int i = 0; i < 6; i++) { CheckNo += hash.Substring(rd.Next(1, hash.Length - 1), 1); } CheckNo = CheckNo.Replace("0", rd.Next(1, 9).ToString()); CheckNo = CheckNo.Replace("o", rd.Next(1, 9).ToString());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值