webform:图片水印、验证码制作

一、图片水印

1:引命名空间System.Drawing;

前端代码

<div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" Text="上传" /><br />
<asp:Image ID="Image1" runat="server" />
</div>

后台代码

//准备画布
System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.FileContent);
//创建画笔
Graphics g = Graphics.FromImage(img); string s = "汉企奇点网络0928";
//画笔的字体
Font f = new Font("微软雅黑",);
//画笔的样式和颜色
Brush b = new SolidBrush(Color.Red);
//在什么位置画
PointF p = new PointF(,);
//画字符串
g.DrawString(s, f, b, p); string sss = "images/"+DateTime.Now.ToString("yyyyMMddhhmmssms")+FileUpload1.FileName; img.Save(Server.MapPath(sss)); Image1.ImageUrl = sss;

二、图片验证码

1:引命名空间System.Drawing;

单独创建一个窗体来绘制验证码

后台代码

protected void Page_Load(object sender, EventArgs e)
{
Bitmap img = new Bitmap(, );
Graphics g = Graphics.FromImage(img);
Random r = new Random();
//创建一个颜色集合 或者也可以通过RGBA颜色直接随机生成
List<Color> clist = new List<Color>();
clist.Add(Color.Yellow);
clist.Add(Color.Green);
clist.Add(Color.Blue);
clist.Add(Color.Pink);
clist.Add(Color.Orange);
clist.Add(Color.Black);
//绘制背景色
g.FillRectangle(new SolidBrush(clist[r.Next(, clist.Count)]), , , , );
//循环随机绘制干扰线
for (int i = ; i < ; i++)
{
Color ccc = clist[r.Next(, clist.Count)]; Pen ppp = new Pen(new SolidBrush(ccc), r.Next(, )); g.DrawLine(ppp, new PointF(r.Next(, ), r.Next(, )), new PointF(r.Next(, ), r.Next(, )));
}
//准备一些字母数字
string all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
string s = "";
//从上面随机出四个字符拼接
for (int i = ; i < ; i++)
{
int a = r.Next(all.Length);
s += all.Substring(a, );
}
//存入Session
Session["YZM"] = s;
//绘制出验证码
g.DrawString(s, new Font("微软雅黑", ), new SolidBrush(Color.Red), new PointF(, ));
//通过流把绘制好的验证码输出出去
img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);
Response.End();
}

界面接收

void Button1_Click(object sender, EventArgs e)
{
string t1 = TextBox1.Text;
string t2 = Session["YZM"].ToString(); if (t1.ToUpper() == t2.ToUpper())
{
Label1.Text = "验证成功!";
}
else
{
Label1.Text = "验证失败!";
}
}

重新生成验证码(JS)

<script type="text/javascript">
var a = ;
document.getElementById("Image1").onclick = function () {
this.setAttribute("src", "yzm.aspx?id=" + a);
a++;
}
</script>
上一篇:Android编译过程详解(一)


下一篇:ActiveMQ持久化消息(转)