- protected void Page_Load(object sender, EventArgs e)
- {
- Bitmap bmp = new Bitmap(80, 40);//定義一個畫布
- Graphics g = Graphics.FromImage(bmp);
- g.Clear(Color.White);
- g.DrawRectangle(Pens.Black, 0, 0, 79, 39);//繪製邊框
- //定義七種顏色
- Color[] colors = { Color.Black, Color.Red, Color.Blue, Color.DarkGreen, Color.Purple, Color.DarkGoldenrod, Color.Chocolate };
- //定義七種字體
- string[] fontNames = { "宋體", "楷體_GB2312", "隸書", "Arial", "Comic Sans MS", "Microsoft Sans Serif", "Times New Roman" };
- //隨機數
- Random rand = new Random();
- //隨機生成驗證字符
- char[] chs = new char[] { (char)(65 + rand.Next(26)), (char)(65 + rand.Next(26)), (char)(65 + rand.Next(26)) };
- Brush brush;//定義畫刷
- Font font;//定義字體
- int x, y;//座標
- for (int i = 0; i < 3; i++)
- {
- brush = new SolidBrush(colors[rand.Next(7)]);
- font = new Font(fontNames[rand.Next(7)], 18, FontStyle.Bold);
- x = i * 20 + 2;
- y = 5 + rand.Next(5);
- g.RotateTransform(rand.Next(-10, 9));
- //畫出字符
- g.DrawString(chs[i].ToString(), font, brush, x, y);
- }
- Pen[] pens = { Pens.Gray, Pens.LightGray };
- for (int i = 0; i < 200; i++)//繪製隨機躁點
- {
- x = rand.Next(bmp.Width - 1);
- y = rand.Next(bmp.Height - 1);
- g.DrawEllipse(pens[i % 2], x, y, 1, 1);
- }
- MemoryStream ms = new MemoryStream();
- bmp.Save(ms, ImageFormat.Jpeg);
- this.Response.Clear();
- this.Response.ContentType = "p_w_picpath/Jpeg";
- this.Response.BinaryWrite(ms.ToArray());//輸出圖像
- g.Dispose();
- bmp.Dispose();
- }