using System.Drawing.Imaging;
private void Page_Load(object sender, System.EventArgs e)
{
drawimg();
}
private void drawimg()
{
Bitmap newBitmap = new Bitmap(36,16,PixelFormat.Format32bppArgb);
//draw image
Graphics g = Graphics.FromImage(newBitmap);
//fill the area with color
g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0,0,36,16));
//set font object
Font textFont = new Font("Verdana",9);
//create RectangleF structure area
RectangleF rectangle = new RectangleF(0,0,36,16);
//set a random object
Random rd = new Random();
//get random number
int valationNo = 1000 + rd.Next(8999);
Session["valation"]=valationNo;
//fill with color
g.FillRectangle(new SolidBrush(Color.BurlyWood), rectangle);
//fill with fonts
g.DrawString(valationNo.ToString(), textFont, new SolidBrush(Color.Blue), rectangle);
//save the image to memory stream
try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
newBitmap.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
//newBitmap.Save(@"C:/Inetpub/wwwroot/test0401/VaImg.gif",ImageFormat.Gif); save it to harddisk
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
validate-page.aspx
...
<img src="image.aspx">
...
private void drawimg()
{
Bitmap newBitmap = new Bitmap(36,16,PixelFormat.Format32bppArgb);
//draw image
Graphics g = Graphics.FromImage(newBitmap);
//fill the area with color
g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0,0,36,16));
//set font object
Font textFont = new Font("Verdana",9);
//create RectangleF structure area
RectangleF rectangle = new RectangleF(0,0,36,16);
//set a random object
Random rd = new Random();
//get random number
int valationNo = 1000 + rd.Next(8999);
Session["valation"]=valationNo;
//fill with color
g.FillRectangle(new SolidBrush(Color.BurlyWood), rectangle);
//fill with fonts
g.DrawString(valationNo.ToString(), textFont, new SolidBrush(Color.Blue), rectangle);
//save the image to memory stream
try
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
newBitmap.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
//newBitmap.Save(@"C:/Inetpub/wwwroot/test0401/VaImg.gif",ImageFormat.Gif); save it to harddisk
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
}
validate-page.aspx
...
<img src="image.aspx">
...
此博客展示了一段C#代码,用于绘制随机验证码图片。代码中创建了Bitmap对象,设置字体、随机数,将随机数绘制到图片上,最后保存图片到内存流并输出。同时还处理了可能出现的异常,给出了页面引用图片的示例。
3万+

被折叠的 条评论
为什么被折叠?



