drawimg.aspx.cs(片段)
private void Page_Load(object sender, System.EventArgs e)
{
// 在這裡放置使用者程式碼以初始化網頁
string valCode = RandomString(int.Parse("7"));
Session.Add("ValCode", valCode);
DrawImage(valCode);
}
private string RandomString(int bit)
{
string chars = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z" ;
string[] charArray = chars.Split(',');
string result = "";
Random rdm = new Random();
for (int i = 0; i < bit; i++)
{
result += charArray[rdm.Next(36)];
}
return result;
}
//?????成?形
private void DrawImage(string valCode)
{
//生成位?
Bitmap bmp = new Bitmap(valCode.Length*20, 25);
Graphics g = Graphics.FromImage(bmp);
try
{
g.Clear(Color.White);
//定義色和字体集
Color[] c = {Color.Red, Color.Green, Color.Navy, Color.DarkCyan, Color.Blue, Color.Purple};
string[] fonts = {"Microsoft Sans Serif", "Times New Roman", "Lucida Console", "Arial", "Verdana"};
//制背景网格
Pen p = new Pen(Color.LightGray, 0);
int y = 5;
do
{
g.DrawLine(p, 0, y, bmp.Width, y);
y += 5;
}
while(y < bmp.Height);
int x = 5;
do
{
g.DrawLine(p, x, 0, x, bmp.Height);
x += 5;
}
while(x < bmp.Width);
Random rdm = new Random();
for (int i = 0; i < valCode.Length; i++)
{
int ci = rdm.Next(c.Length);
int fi = rdm.Next(fonts.Length);
Font f = new Font(fonts[fi], 12, FontStyle.Bold);
Brush b = new SolidBrush(c[ci]);
g.DrawString(valCode.Substring(i,1), f, b, 5+(i*14), rdm.Next(2,5));
}
g.DrawRectangle(p, 0, 0, bmp.Width-1, bmp.Height-1);
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.Cache.SetNoStore();
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
Response.End();
}
這樣用:
<img = "drawimg.aspx">
浙公网安备 33010602011771号