从别人的那里拿了一个,但是背景颜色太深,看起来不舒服,我也改不好那个背景色,就向大家求一个
最好带上代码和前台调用的方法。

解决方案 »

  1.   

    using System.Drawing;
     using System.Drawing.Imaging;
     using System.IO;
     using System.Text;
     
     
     
    protected void Page_Load(object sender, EventArgs e)
         {
              string chkCode = string.Empty;
             //颜色列表,用于验证码、噪线、噪点
             Color[] color = { Color.Black, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue, Color.Red, Color.Purple, Color.Chocolate };
             //字体列表,用于验证码
             string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact", "Arial" };
             char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k', 'm', 'n', 'p', 'r', 's', 't', 'w', 'x', 'y' };
             Random rnd = new Random();
             //给验证码随机3个西文字符
             for (int i = 0; i < 3; i++)
             {
                 chkCode += character[rnd.Next(character.Length)];
             }
             //再随机加一个中文字符
             chkCode+=GeberateChineseCheckCode(1);
             //保存验证码的Cookie
             HttpCookie anycookie = new HttpCookie("validateCookie");
             anycookie.Values.Add("ChkCode", chkCode);
             HttpContext.Current.Response.Cookies["validateCookie"].Values["ChkCode"] = chkCode;
             Bitmap bmp = new Bitmap(90, 30);
             Graphics g = Graphics.FromImage(bmp);
             g.Clear(Color.White);
             //画噪线
             //for (int i = 0; i < 2; i++)
             //{
             //    int x1 = rnd.Next(90);
             //    int y1 = rnd.Next(30);
             //    int x2 = rnd.Next(90);
             //    int y2 = rnd.Next(30);
             //    Color clr = color[rnd.Next(color.Length)];
             //    g.DrawLine(new Pen(clr), x1, y1, x2, y2);
             //}
             //画验证码字符串
             for (int i = 0; i < chkCode.Length; i++)
             {
                 string fnt = font[rnd.Next(font.Length)];
                 Font ft = new Font(fnt, 14);
                 Color clr = color[rnd.Next(color.Length)];
                 g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 , (float)3);
             }
             //画噪点
             for (int i = 0; i < 150; i++)
             {
                 int x = rnd.Next(bmp.Width);
                 int y = rnd.Next(bmp.Height);
                 Color clr = color[rnd.Next(color.Length)];
                 bmp.SetPixel(x, y, clr);
             }
             //清除该页输出缓存,设置该页无缓存
             Response.Buffer = true;
             Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
             Response.Expires = 0;
             Response.CacheControl = "no-cache";
             Response.AppendHeader("Pragma", "No-Cache");
             //将验证码图片写入内存流,并将其以"image/Png" 格式输出
             MemoryStream ms = new MemoryStream();
             try
             {
                 bmp.Save(ms, ImageFormat.Png);
                 Response.ClearContent();
                 Response.ContentType = "image/Png";
                 Response.BinaryWrite(ms.ToArray());
             }
             finally
             {
                 //显式释放资源
                 bmp.Dispose();
                 g.Dispose();
             }
         }
     
      /// <summary>
         /// 产生随机验证码,可选用
         /// </summary>
         /// <returns></returns>
         string GenerateCheckCode()
         {
             int number;
             string randomCode = string.Empty;
             Random r = new Random();
             for (int i = 0; i < 5; i++)
             {
                 number = r.Next();
                 number = number % 36;
                 if (number < 10)
                 {
                     number += 48;
                 }
                 else
                 {
                     number += 55;
                 }
                 randomCode += ((char)number).ToString();
             }
             Response.Cookies.Add(new HttpCookie("CheckCode", randomCode));
             return randomCode;
         }
     
     /// <summary>
         /// 产生中文的随机验证码,可选用
         /// </summary>
         /// <returns></returns>
         string GeberateChineseCheckCode(int strLength)
         {
             string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
             Random rnd = new Random();
             object[] bytes = new object[strLength];
             for (int i = 0; i < strLength; i++)
             {
                 //区位码第1位
                 int r1 = rnd.Next(11, 14);
                 string str_r1 = rBase[r1].Trim();
                 //区位码第2位
                 rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机数发生器的种子避免产生重复值
                 int r2;
                 if (r1 == 13)
                 {
                     r2 = rnd.Next(0, 7);
                 }
                 else
                 {
                     r2 = rnd.Next(0, 16);
                 }
                 string str_r2 = rBase[r2].Trim();
                 //区位码第3位
                 rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
                 int r3 = rnd.Next(10, 16);
                 string str_r3 = rBase[r3].Trim();
                 //区位码第4位
                 rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
                 int r4;
                 if (r3 == 10)
                 {
                     r4 = rnd.Next(1, 16);
                 }
                 else if (r3 == 15)
                 {
                     r4 = rnd.Next(0, 15);
                 }
                 else
                 {
                     r4 = rnd.Next(0, 16);
                 }
                 string str_r4 = rBase[r4].Trim();
                 //定义两个字节变量存储产生的随机汉字区位码
                 byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
                 byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
                 //将两个字节变量存储在字节数组中
                 byte[] str_r = new byte[] { byte1, byte2 };
                 //将产生的一个汉字的字节数组放入object数组中
                 bytes.SetValue(str_r, i);
             }
             //获取GB2312编码页(表)
             Encoding gb = Encoding.GetEncoding("gb2312");
             string temp;
             string result = string.Empty;
             for (int i = 0; i < strLength; i++)
             {
                 temp = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
                 result += temp;
             }
             return result;
         }
      

  2.   

    其实我的这个也不咋好 感觉燥化太严重了 你可以稍微改改
    showimage.aspxusing System;
    using System.Data;
    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;public partial class ShowImage : System.Web.UI.Page
    {
        
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                Session["CheckCodes"] = RandomNum(4);
                CheckCodes(Session["CheckCodes"].ToString());
            }
        }
        public string RandomNum(int n)
        {
            string strchar = "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,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 = strchar.Split(',');
            string VNum = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 1; i < n + 1; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));            }
                int t = rand.Next(61);
                if (temp != -1 && temp == t)
                {
                    return RandomNum(n);
                }
                temp = t;
                VNum += VcArray[t];
            }
            return VNum;
        }    public void CheckCodes(string CheckCode)
        {
            Random rand = new Random();
            int iwidth = (int)(CheckCode.Length * 15);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 22);
            Graphics g = Graphics.FromImage(image);
            g.Clear(Color.White);
            //画图片的背景噪音线20条
            for (int i = 0; i < 20; i++)
            {
                int x1 = rand.Next(image.Width);
                int x2 = rand.Next(image.Width);
                int y1 = rand.Next(image.Height);
                int y2 = rand.Next(image.Height);
                g.DrawLine(new Pen(Color.Silver), x1, x2, y1, y2);
            }
            //定义颜色
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple, Color.YellowGreen };
            //定义字体 
            string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体", "新宋体" };        //输出不同字体和颜色的验证码字符
            for (int i = 0; i < CheckCode.Length; i++)
            {
                int cindex = rand.Next(7);
                int findex = rand.Next(6);            Font f = new System.Drawing.Font(font[findex], 12, System.Drawing.FontStyle.Bold);
                Brush b = new System.Drawing.SolidBrush(c[cindex]);
                int ii = 4;
                if ((i + 1) % 2 == 0)
                {
                    ii = 2;
                }
                g.DrawString(CheckCode.Substring(i, 1), f, b, 3 + (i * 12), ii);
            }
            //画一个边框        g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);        //输出到浏览器
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            HttpContext.Current.Response.ClearContent();
            //Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/Png";
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }
    }前台<tr height="30">
      <td align="right">验&nbsp;证&nbsp;码:</td>
      <td align="left"><asp:TextBox ID="checkcode" runat="server" CssClass="textborder2"></asp:TextBox>
          <img id="CheckCodesy" style="vertical-align: top; cursor:pointer" alt="点击换一张" src="ShowImage.aspx?temp='+ (new Date().getTime().toString(36)) +'" onclick="document.getElementById('CheckCodesy').src='ShowImage.aspx?temp='+(new Date().getTime().toString(36)); return false" />
      </td>
    </tr>
      

  3.   

     private void Page_Load(object sender, System.EventArgs e)
        {
            string checkCode = CreateRandomCode(4);
            Session["CheckCode"] = checkCode;
            CreateImage(checkCode);
        }    private string CreateRandomCode(int codeCount)
        {
            string allChar = "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,W,X,Y,Z";
            string[] allCharArray = allChar.Split(',');
            string randomCode = "";
            int temp = -1;        Random rand = new Random();
            for (int i = 0; i < codeCount; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                if (temp == t)
                {
                    return CreateRandomCode(codeCount);
                }
                temp = t;
                randomCode += allCharArray[t];
            }
            return randomCode;
        }    private void CreateImage(string checkCode)
        {
            int iwidth = (int)(checkCode.Length * 11.5);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
            Graphics g = Graphics.FromImage(image);
            Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(Color.White);
            //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
            g.Clear(Color.Green);
            g.DrawString(checkCode, f, b, 3, 3);        Pen blackPen = new Pen(Color.Black, 0);
            Random rand = new Random();
            for (int i = 0; i < 5; i++)
            {
                //int y = rand.Next(image.Height);
                //g.DrawLine(blackPen, 0, y, image.Width, y);
            }        System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            Response.ClearContent();
            Response.ContentType = "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }
      

  4.   


     <asp:ImageButton ID="ImgValidateCode" TabIndex="5" ToolTip="点击更换图片" ImageUrl="ValidateCode.aspx"
                                                OnClick="ImgValidateCode_Click" runat="server" />
        protected void ImgValidateCode_Click(object sender, ImageClickEventArgs e)
        {
            ImgValidateCode.ImageUrl = "ValidateCode.aspx";
        }
      

  5.   

    小生  
    看不懂大家伙的。帮我看看这个代码的背景色怎么改改能好看点,背景是蓝色的太重了 private void CreateImage(string checkCode)
        {
            int iwidth = (int)(checkCode.Length * 11.5);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
            System.Drawing.Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);
            System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.White);
            //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
            g.Clear(System.Drawing.Color.Blue);
            g.DrawString(checkCode, f, b, 3, 3);        System.Drawing.Pen blackPen = new System.Drawing.Pen(System.Drawing.Color.Black, 0);
            Random rand = new Random();
            for (int i = 0; i < 5; i++)
            {
                int y = rand.Next(image.Height);
                g.DrawLine(blackPen, 0, y, image.Width, y);
            }        System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            Response.ClearContent();
            Response.ContentType = "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            image.Dispose();
        }
      

  6.   


    g.Clear(System.Drawing.Color.Blue);
    这不是Blue吗,改这个就行了
      

  7.   


    System.Drawing.Pen blackPen = new System.Drawing.Pen(System.Drawing.Color.Black, 0);
      Random rand = new Random();
      for (int i = 0; i < 5; i++)
      {
      int y = rand.Next(image.Height);
      g.DrawLine(blackPen, 0, y, image.Width, y);
      }这块是划线的,你看着办吧,赶紧姐贴吧
      

  8.   

    不想要了就把
     g.DrawLine(blackPen, 0, y, image.Width, y);注释了
      

  9.   

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.Web;
    using System.Web.SessionState;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using System.IO;public partial class YangZhengMa : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CreateValidateImage(CreateValidateKey(4));
        }    private string CreateValidateKey(int num)
    {
    //string str = "的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府称太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严";
    //char[] chastr = str.ToCharArray();
    //string[] source ={ "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[] source ={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
                string code = "";
    Random rd = new Random();
    int i;
    for (i = 0; i < num; i++)
    {
    code += source[rd.Next(0, source.Length)];
    //code += str.Substring(rd.Next(0, str.Length), 1);//随机取一个汉字
    }
    return code;
    } private void CreateValidateImage(string checkCode)
    {
    if (checkCode.Trim() == "" || checkCode == null)
    return;
    Session["Code"] = checkCode; //将字符串保存到Session中,以便需要时进行验证 System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)(checkCode.Length * 21.5), 22);
    Graphics g  = Graphics.FromImage(image);//通过image对象产生描绘对象g
    try
    {
    //生成随机生成器
    Random random = new Random();  //清空图片背景色
    g.Clear(Color.White);   // 画图片的背景噪音线
    int i;
    for (i = 0; i < 25; i++)
    {
    int x1 = random.Next(image.Width);
    int x2 = random.Next(image.Width);
    int y1 = random.Next(image.Height);
    int y2 = random.Next(image.Height);
    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);//画一个矩形
    }
                    //字体
    Font font = new System.Drawing.Font("黑体", 18, (System.Drawing.FontStyle.Bold));
    //画刷
                    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.DarkRed, 1.6F, true);
    //写汉字
    g.DrawString(checkCode, font, brush, 0, 0); //画图片的前景噪音点
    g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
    System.IO.MemoryStream ms = new System.IO.MemoryStream();//内存流
    //保存到内存流
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    //清空响应流内容
    Response.ClearContent();
    //设置响应流内容格式
    Response.ContentType = "image/Gif";
    //将内存流中的图片写入响应流
    Response.BinaryWrite(ms.ToArray());
    }
    catch
    {
    g.Dispose();
    image.Dispose();
    }
    }
    }
      

  10.   

    <img src="YangZhengMa.aspx" runat="server" id="kk" onclick="this.src='YangZhengMa.aspx?id='+Math.random()" width="72" height="27" />
    调用的