c#生成图片验证码代码

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

前台引用.aspx:
看不清楚,请单击我。




YanZhengCode.cs
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.IO;

public partial class YanZhengCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string str = Request["chen"];
BuildCode();

//ShuImg();
}

private void BuildCode()

{

Color[] strcolor ={ Color.Red, Color.Blue, Color.Brown,Color.Black,Color.Tomato };

string[] strfont={"华文中宋"};
Random rands = new Random();
Bitmap images = new Bitmap(80,26); //图片大小
Graphics g = Graphics.FromImage(images);
Font f = new Font(strfont[0], 20); //字体大小

//笔刷填充色
Brush b = new SolidBrush(Color.Tomato);
Brush b2 = new SolidBrush(strcolor[rands.Next(0,strcolor.Length)]);
Brush b3 = new SolidBrush(Color.Red);
Brush b4 = new SolidBrush(Color.FromArgb(128,Color.Green));
g.Clear(Color.Wheat);

//线条颜色
Pen p = new Pen(Color.Red, 0);
Pen p2 = new Pen(Color.Turquoise,0);
Random rand = new Random();
for (int i = 0; i < 40; i++)
{
int y = rand.Next(images.Height);
int x = rand.Next(images.Width);
//g.DrawLine(p, 0, y, images.Width, y);
g.DrawRectangle(p2, x, y, 1, 1);
}
//int degree = 5;
//Point tempPoint = new Point();
//degree = ~degree + 1;
//g.RotateTransform(degree);
//tempPoint.X = 20;
//tempPoint.Y = 4;

g.DrawRectangle(p, 0, 0, images.Width-1, images.Height-1); //绘图区域
string strCode = rand.Next(1000,10000).ToString();
Session["yanzhencode"] = strCode;
g.DrawString(strCode.Substring(0, 1), f, b, 2,-1);
g.DrawString(strCode.Substring(1, 1), f, b2, 19, -1);
g.DrawString(strCode.Substring(2, 1), f, b3, 37, -1);
g.DrawString(strCode.Substring(3, 1), f, b4, 50, -1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
images.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/jpeg";
Response.BinaryWrite(ms.ToArray());
//Response.Cookies.Add(new HttpCookie("chne", "6780"));
g.Dispose();
images.Dispose();
}

private void ShuImg()
{
Response.ContentType = "image/*"; //设置发送头为图像数据
Response.Clear(); //清空发送数据
Random rand = new Random();
Stream stream = OpenFile(Server.MapPath("pic/"+rand.Next(1,6).ToString()+".jpg")); //打开文件流
Bitmap bit = new Bitmap(stream);
bi

t.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//保存到输出流中
stream.Close();
bit.Dispose();
Response.Flush(); //输出到客户端
}
}







相关文档
最新文档