Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)归海一刀
published in(发表于) 2014/1/30 1:26:12
c#生成图片验证码代码_[Asp.Net教程]

c#生成图片验证码代码_[Asp.Net教程]











前台引用.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);
bit.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//保存到输出流中
stream.Close();
bit.Dispose();
Response.Flush(); //输出到客户端
}
}














If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759