C#绘制验证码图片

来源:互联网 发布:ucosii 软件定时器 编辑:程序博客网 时间:2024/04/28 06:31
    //验证码生成,注意宽高与字体比例,字体大小是高度/2.4
    private void SetValidateCode(string value,int width,int height)
    
{
        
//新建位图
        Bitmap newBitmap = new Bitmap(
                                        width,
                                        height,
                                        PixelFormat.Format32bppArgb
                                     );
        
//从位图获得绘图画面
        Graphics g = Graphics.FromImage(newBitmap);
        
//随机数生成器
        Random r = new Random();
        
//绘图画面清空
        g.Clear(Color.White);
        
//绘图画面划线干扰
        for (int i = 0; i < 50; i++)
        
{
            
int x1 = r.Next(newBitmap.Width);
            
int x2 = r.Next(newBitmap.Width);
            
int y1 = r.Next(newBitmap.Height);
            
int y2 = r.Next(newBitmap.Height);
            g.DrawLine(
new Pen(
                                Color.FromArgb(r.Next())),
                                x1,
                                y1,
                                x2,
                                y2
                              );
        }

        
//绘图画面点数干扰
        for (int i = 0; i < 100; i++)
        
{
            
int x = r.Next(newBitmap.Width);
            
int y = r.Next(newBitmap.Height);
            newBitmap.SetPixel(
                                x,
                                y,
                                Color.FromArgb(r.Next())
                              );
        }

        
//定义图片显示字体样式
        Font font = new Font(
                               
"Arial",
                               Convert.ToInt16(height
/2.4),
                               FontStyle.Bold
                            );
        Random rr 
= new Random();
        
int yy = rr.Next(14);
        
//定义随机字符串显示图片刷子
        LinearGradientBrush brush = new LinearGradientBrush(
                                                              
new Rectangle(00, width,height),
                                                              Color.Red,
                                                              Color.Blue,
                                                              
1.2f,
                                                              
true
                                                           );
        g.DrawString(value, font, brush, 
2, yy);
        g.DrawRectangle(
new Pen(Color.Silver),
                                  
0,
                                  
0,
                                  width
-1,
                                  height
-1
                                );
        System.IO.MemoryStream ms 
= new System.IO.MemoryStream();
        newBitmap.Save(ms, ImageFormat.Gif);
        
//输出图片
        Response.ClearContent();
        Response.ContentType 
= "image/gif";
        Response.BinaryWrite(ms.ToArray());
    }
原创粉丝点击