using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Drawing; using System.Drawing.Imaging; using System.IO; public partial class image : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string tmp = RanNum(4); HttpCookie a = new HttpCookie("ImageV",tmp); Response.Cookies.Add(a); this.ValidateCode(tmp); } public void ValidateCode(string VNum) { Bitmap Img = null; Graphics g = null; MemoryStream ms = null; int gheight = VNum.Length * 2; Img = new Bitmap(gheight,25); g = Graphics.FromImage(Img); //设定背景颜色 g.Clear(Color.White); //文字字体 Font f=new Font ("Arial Black",10); //文字颜色 SolidBrush s = new SolidBrush(Color.Black); g.DrawString(VNum,f,s,3,3); ms = new MemoryStream(); Img.Save(ms,ImageFormat.Jpeg); Response.ClearContent(); Response.ContentType = "image/jpeg"; Response.BinaryWrite(ms.ToArray()); g.Dispose(); Img.Dispose(); Response.End(); } private string RanNum(int VCodeNum) { string Vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p," + "q,r,s,t,u,v,w,x,y,z"; string[] VcArray = Vchar.Split(new char []{','}); string VNum = ""; int Temp = -1; Random rand = new Random(); for (int i = 1; i < VCodeNum + 1; i++) { if (Temp != -1) { rand = new Random(i * Temp * unchecked((int)DateTime.Now.Ticks)); } int t = rand.Next(35); if (Temp != -1 && Temp == t) { return RanNum(VCodeNum); } Temp = t; VNum += VcArray[t]; } return VNum; } }
上边的这个是image.aspx.cs的代码
下边是测试页的代码:
1Default.aspx
<asp:ImageButton ID="ImageButton1" runat="server" />
2
Default.aspx.cs代码
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { ImageButton1.ImageUrl = "image.aspx"; } }
结果却是这样的:只显示一点,不能显示完整的验证码,求原因,谢谢
Img = new Bitmap(gheight,25); 你把gheight用一个具体的数据代替试下,因为三个字符的话,长度就为3,3px有多大呢?肯定不够显示三个字符的。。。
没设置大小吧。。。