首页 > 代码库 > webform:图片水印、验证码制作
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("微软雅黑",20); //画笔的样式和颜色 Brush b = new SolidBrush(Color.Red); //在什么位置画 PointF p = new PointF(20,20); //画字符串 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(80, 40); 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(0, clist.Count)]), 0, 0, 80, 40); //循环随机绘制干扰线 for (int i = 0; i < 10; i++) { Color ccc = clist[r.Next(0, clist.Count)]; Pen ppp = new Pen(new SolidBrush(ccc), r.Next(1, 5)); g.DrawLine(ppp, new PointF(r.Next(0, 80), r.Next(0, 40)), new PointF(r.Next(0, 80), r.Next(0, 40))); } //准备一些字母数字 string all = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string s = ""; //从上面随机出四个字符拼接 for (int i = 0; i < 4; i++) { int a = r.Next(all.Length); s += all.Substring(a, 1); } //存入Session Session["YZM"] = s; //绘制出验证码 g.DrawString(s, new Font("微软雅黑", 16), new SolidBrush(Color.Red), new PointF(3, 3)); //通过流把绘制好的验证码输出出去 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 = 0; document.getElementById("Image1").onclick = function () { this.setAttribute("src", "yzm.aspx?id=" + a); a++; } </script>
webform:图片水印、验证码制作
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。