C#或ASP.NET的简单绘图
1 public void ProcessRequest (HttpContext context) { 2 context.Response.ContentType = "img/JPEG"; 3 using(System.Drawing.Bitmap bm=new System.Drawing.Bitmap(300,100))//规定大小 4 { 5 using(System.Drawing.Graphics g=System.Drawing.Graphics.FromImage(bm))//图像化 6 { 7 g.DrawString("腾讯QQ",new Font("楷体",40),Brushes.Green,new PointF(10,10)); 8 g.DrawEllipse(Pens.AliceBlue,new Rectangle(200,10,80,80)); 9 bm.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);//保存到网页 10 } 11 } 12
下面这个例子是一个验证码问题
先是example.asph文件
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <div><img src="AddCalation.ashx"onclick="this.src=‘AddCalation.ashx?aaa=‘+new Date()" /></div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> </div> </form> </body> </html>
然后是example.aspx.cs文件
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class TestCode : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string code = Session["test"].ToString(); if(code==TextBox1.Text) { Response.Write("匹配正确"); } else { Response.Write("匹配错误"); } } }
再是验证码图片创造文件example.ashx
1 <%@ WebHandler Language="C#" Class="AddCalation" %> 2 3 using System; 4 using System.Web; 5 using System.Drawing; 6 public class AddCalation : IHttpHandler,System.Web.SessionState.IRequiresSessionState{ 7 8 public void ProcessRequest (HttpContext context) { 9 context.Response.ContentType = "img/JPEG"; 10 using(System.Drawing.Bitmap bm=new System.Drawing.Bitmap(150,60)) 11 { 12 using(System.Drawing.Graphics g=System.Drawing.Graphics.FromImage(bm)) 13 { 14 Random rand = new Random(); 15 int code = rand.Next(); 16 string testcode=code.ToString().Substring(0,4); 17 HttpContext.Current.Session["test"] = testcode; 18 g.DrawString(testcode,new Font("楷体",40),Brushes.Green,new PointF(10,5)); 19 20 bm.Save(context.Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg); 21 } 22 } 23 24 25 } 26 27 public bool IsReusable { 28 get { 29 return false; 30 } 31 } 32 33 }
执行效果如下图