using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;public partial class RandomImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
createimg(createcode());
} //生成随机数
private string createcode()
{
int codelength = 4;
int num;
string randcode="";
Random r = new Random();
for (int i = 0; i < codelength; i++)
{
num = r.Next();
num = num % 36;
if (num < 10)
num += 48;
else
num += 55;
randcode += ((char)num).ToString();
}
//保存生成的字符串,winform中可以保存为文本文件
Response.Cookies.Add(new HttpCookie("checkcode",randcode));
return randcode;
} //生成图片
private void createimg(string checkcode)
{
if (checkcode == null || checkcode == "")
return;
int imgwidth = (int)Math.Ceiling(checkcode.Length*15m);
int imgheight = 22;
Bitmap img=new Bitmap(imgwidth,imgheight);
Graphics g = Graphics.FromImage(img); try
{
Random r = new Random();
g.Clear(Color.White);
for (int i = 0; i < 10; i++)
{
int x1 = r.Next(img.Width);
int x2 = r.Next(img.Width);
int y1 = r.Next(img.Height);
int y2 = r.Next(img.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
} for (int i = 0; i < 50; i++)
{
int x = r.Next(img.Width);
int y = r.Next(img.Height);
img.SetPixel(x, y, Color.FromArgb(r.Next()));
} g.DrawRectangle(new Pen(Color.SaddleBrown), 0, 0, img.Width - 1, img.Height - 1);
Font f = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Blue, Color.Purple, 1.2f, true);
g.DrawString(checkcode, f, brush, 2, 2); using (MemoryStream ms = new MemoryStream())
{
//因为你是winform程序可以直接用image.fromstream(ms);来输出图片
img.Save(ms, ImageFormat.Png);
Response.ClearContent();
Response.ContentType = "image/Png";
Response.BinaryWrite(ms.ToArray());
}
}
finally
{
g.Dispose();
img.Dispose();
}
}
}
按注释改下
和web的一样!画一个图片!上面画数字!随机的画!