现在的位置: 首页 > 综合 > 正文

一个可设置背景图片的验证码图片的生成方法

2013年09月17日 ⁄ 综合 ⁄ 共 1278字 ⁄ 字号 评论关闭

参数说明:

sourceFile:背景图片文件

text:要显示的文本

public void MakeCheckImage(string sourceFile,string text)
  {
   Response.Clear();
   try
   {
    //原图
    Bitmap sImage = new Bitmap(sourceFile);    
   
    //验证码图
    Bitmap wImage = new Bitmap(100,30,System.Drawing.Imaging.PixelFormat.Format24bppRgb);    
    Graphics wg = Graphics.FromImage(wImage);
    wg.Clear(Color.White);
    wg.DrawString(text,new Font("Verdana",18),new SolidBrush(Color.Black),0,0);
    wg.Save();
    
    //make Graphics.
    Graphics g = Graphics.FromImage(sImage);
    int x; //临时变量
    int y; //监时变量    
    int w = 100; //验证图的宽度
    int h = 30; //验证图的高度
    int al; //alpha
    int rl; //Red
    int gl; //Green
    int bl; //Blue
    
    //开始绘图
    for(x = 1; x < w; x++)
    {
     for(y = 1; y < h; y++)
     {
      al = wImage.GetPixel(x,y).A;
      rl = wImage.GetPixel(x,y).R;
      gl = wImage.GetPixel(x,y).G;
      bl = wImage.GetPixel(x,y).B;
      al = 70;
     
      if(rl - 50 > 0)
       rl -= 50;
      if(gl - 50 > 0)
       gl -= 50;
      if(bl - 50 > 0)
       bl -= 50;
      g.DrawEllipse(new Pen(new SolidBrush(Color.FromArgb(al,rl,gl,bl))),x,y,1,1);           
     }
    }  
    g.Save();
    sImage.Save(Response.OutputStream,ImageFormat.Jpeg);    
    wg.Dispose();
    g.Dispose();
    sImage.Dispose();
    wImage.Dispose();    
   }
   catch(Exception e)
   {
    Response.Write(e.Message);
   } 
   Response.End();
  }


抱歉!评论已关闭.