在创建网站中验证码是不可或缺的。可以利用BinaryWrite输出二进制图像的方法输出验证码。

在开发图形验证码时,首先生成验证码,然后绘制成图像,最后通过该方法输出到页面中。所以熟练地掌握该方法可以为以后开发图形验证码奠定基础。首先定义个字符串数组,随机去除一个用来做验证码。根据字符串长度创建一个画布Bitmap,接着在Bitmap对象上绘制边框,背景颜色,背景噪音线和前景噪音线,并且将绘制后的二进制图像保存到内存流中,最后通过Response对象的BinaryWrite方法输出到浏览器中。代码如下

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging; public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//生成随机生成器
Random random = new Random();
//成语字符串数组,随机去除创建验证码
string[] str = { "海阔天高", "望子成龙", "守株待兔", "国足无敌", "点石成金", "天涯明月", "尧尧无敌", "一望无际" };
//string checkCode = "海阔天高";
int count = random.Next(str.Length);
string checkCode = str[count];
//根据字符串长度创建一个Bitmap画布
Bitmap image = new Bitmap((int)Math.Ceiling((checkCode.Length * 20.5)), );
Graphics g = Graphics.FromImage(image);
try
{
g.Clear(Color.White);//清空图片背景色
for (int i = ; i < ; i++)//生成两条随机的噪音线
{
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.Black), x1, y1, x2, y2);
}
Font font = new Font("Arial", , (FontStyle.Bold));//定义字体
LinearGradientBrush brush = new LinearGradientBrush(
new Rectangle(, , image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, , );
//画图片前景噪音点
for (int i = ; i < ; 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.Silver), , , image.Width - , image.Height - );
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
}

最新文章

  1. Ubuntu 14.04开发环境初始化
  2. declaration expected but identifier &#39;firedac&#39; found
  3. 移动web开发之移动端真机测试
  4. Java读取txt文件
  5. HBase的安装与使用
  6. OC与Swift的区别四(条件语句)
  7. jquery获取元素方式
  8. PHP开发APP接口
  9. 第二章排错的工具:调试器Windbg(上)
  10. Python科学计算之Pandas
  11. SpringMVC获取页面数据乱码的解决get/post
  12. Tensorflow卷积神经网络
  13. sklearn.linear_model.LogisticRegression参数说明
  14. ArcSDE10.1配置Oracle 监听器来使用SQL操作ST_Geometry(个人改动版)
  15. 09-HTML-form标签
  16. mongodb安装及配置
  17. vb.net Function使用
  18. OCM_第十八天课程:Section8 &mdash;》RAC 数据库 _ RAC DB 搭建/RAC DB 配置使用
  19. poj3728 倍增法lca 好题!
  20. php整理

热门文章

  1. SQL中获取最近的N个半年度
  2. oracle树操作(select start with connect by prior)
  3. 数据结构--树状数组&amp;&amp;线段树--基本操作
  4. 微信微博分享注意事项(sharesdk)
  5. Flume practices and sqoop hive 2 oracle
  6. js开发工具箱
  7. 如此低价的ZBrush,你能想象?
  8. java解惑 读书笔记
  9. 2014 Super Training #6 H Edward&#39;s Cola Plan --排序+二分
  10. java 20 -3 递归之删除特定目录下的特定文件