public string RandomWords(int maxLength)
        {
            
string words = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
            
string[] wordsArr = words.Split(new char[] { ',' });
            Random random 
= new Random();
            
string code = string.Empty;
            
for (int i = 0; i < maxLength; i++)
            {
                code 
+= wordsArr[random.Next(033)];
            }
            
return code;
        }

        
public void CreateImage(string content)
        {
            
//图片长度
            int imageWidth = (int)(content.Length * 15);
            
//创建位图
            Bitmap image = new Bitmap(imageWidth, 23);
            
//根据图片大小生成画板
            Graphics grap = Graphics.FromImage(image);
            
//字体
            Font font = new Font("Arial"14, FontStyle.Italic);
            
//笔刷
            Brush brush = new SolidBrush(Color.FromArgb(2040240));
            
//生成画板背景
            grap.Clear(Color.FromArgb(235,235,235));
            
//画笔
            Pen pen = new Pen(Color.White,1);
            
//生成三条背景线
            Random random = new Random();
            
for(int i = 0; i < 3; i++)
            {
                
int y = random.Next(image.Height);
                grap.DrawLine(pen,
0,y,image.Width,y);
            }
            
//在画板上画随机码内容
            grap.DrawString(content,font,brush,1,1);

            
//增加随机噪点
            Random randomPoints = new Random((int)DateTime.Now.Ticks);
            Random randomXY 
= new Random(unchecked((int)DateTime.Now.Ticks));
            
for (int i = 0; i < 10; i++)
            {
                
int x = random.Next(image.Width);
                
int y = random.Next(image.Height);

                grap.DrawLine(
new Pen(Color.FromArgb(randomPoints.Next(0255), randomPoints.Next(0255), randomPoints.Next(0255)), 1), x, y, x + randomXY.Next(010), y + randomXY.Next(010)); 
            }

            
for (int i = 0; i < 100; i++)
            {
                
int x = random.Next(image.Width);
                
int y = random.Next(image.Height);

                grap.DrawLine(
new Pen(Color.FromArgb(randomPoints.Next(0255), randomPoints.Next(0255), randomPoints.Next(0255)), 0), x, y, x + randomXY.Next(03), y + randomXY.Next(03));
            }
            
            
//以流的形式返回图片
            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());
            grap.Dispose();

            image.Dispose();

        }

posted on 2009-02-03 14:55  .Net Learning  阅读(751)  评论(0编辑  收藏  举报