using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;
using System.Web.SessionState;
using System.Text;
using System.Collections;
public class CreateImage1 : IHttpHandler, IRequiresSessionState
{
string[] FontItems = new string[] { "Arial",
"Helvetica",
"Geneva",
"sans-serif",
"Verdana"
};
Brush[] BrushItems = new Brush[] { Brushes.OliveDrab,
Brushes.ForestGreen,
Brushes.DarkCyan,
Brushes.LightSlateGray,
Brushes.RoyalBlue,
Brushes.SlateBlue,
Brushes.DarkViolet,
Brushes.MediumVioletRed,
Brushes.IndianRed,
Brushes.Firebrick,
Brushes.Chocolate,
Brushes.Peru,
Brushes.Goldenrod
};
string[] BrushName = new string[] { "OliveDrab",
"ForestGreen",
"DarkCyan",
"LightSlateGray",
"RoyalBlue",
"SlateBlue",
"DarkViolet",
"MediumVioletRed",
"IndianRed",
"Firebrick",
"Chocolate",
"Peru",
"Goldenrod"
};
Color BackColor = Color.White;
Pen BorderColor = Pens.DarkGray;
int Width = 200;
int Height = 60;
Random r = new Random();
int _brushNameIndex;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
Bitmap b = new Bitmap(200, 60);
Graphics g = Graphics.FromImage(b);
g.FillRectangle(new SolidBrush(Color.DarkGray), 0, 0, Width, Height);
Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
StringBuilder sb = new StringBuilder();
//字符串集合
string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz";
string letter;
g.Clear(BackColor);//填充背景色
for (int i = 0; i < 5; i++)
{
letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
sb.Append(letter);
g.DrawString(letter, GetFont(), GetBrush(), i * 38, r.Next(0, 15));
}
for (int n = 0; n < 30; n++)
{
int x = r.Next(200);
int y = r.Next(60);
b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex]));
}
g.DrawRectangle(BorderColor, 0, 0, Width - 1, Height - 1);
//Pen linkPen = new Pen(new SolidBrush(Color.Black), 1);
//for (int i = 0; i < 20; i++)
//{
// g.DrawLine(linkPen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
//}
b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
context.Session["validatecode"] = sb.ToString();
}
private Font GetFont()
{
int fontIndex = r.Next(0, FontItems.Length);
FontStyle fontStyle = GetFontStyle(r.Next(0, 2));
return new Font(FontItems[fontIndex], 24, fontStyle);
}
// 取一个字体的样式
private FontStyle GetFontStyle(int index)
{
switch (index)
{
case 0:
return FontStyle.Bold;
case 1:
return FontStyle.Italic;
default:
return FontStyle.Regular;
}
}
// 随机取一个笔刷
private Brush GetBrush()
{
int brushIndex = r.Next(0, BrushItems.Length);
_brushNameIndex = brushIndex;
return BrushItems[brushIndex];
}
// 绘画背景颜色
private void Paint_Background(Graphics g)
{
g.Clear(BackColor);
}
// 绘画边框
private void Paint_Border(Graphics g)
{
g.DrawRectangle(BorderColor, 0, 0, Width - 1, Height - 1);
}
public bool IsReusable
{
get
{
return false;
}
}
}
使用时,将IMAGE的SRC="createimage.ashx" 就可以了
效果图如下:
请发表评论