使用GDI+在ASP.NET中绘制图形 下面这个例子演示了如何在ASP.NET中绘制矩形、三角形等简单的图形。首先新建一个.aspx文件,取名为Image.aspx,添加对 System.Drawing and System.Drawing.Imaging的引用,将下面的代码复制到Page_Load事件中。
Bitmap bmp = new Bitmap(100, 300); Graphics dc = Graphics.FromImage(bmp); Pen bluePen = new Pen(Color.Blue, 3); dc.DrawRectangle(bluePen, 0, 0, 50, 50); Pen redPen = new Pen(Color.Red, 2); dc.DrawEllipse(redPen, 0, 50, 80, 60); Response.ContentType = "p_w_picpath/gif"; bmp.Save(Response.OutputStream, ImageFormat.Gif);
在上面的代码中,绘制了一个长宽都为50的矩形和一个宽80、高50的三角形。当你在浏览器中打开这个页面时,你看到的是一个图片类型的文件。如果你在页面中添加“This is my p_w_picpath!”这样的文字,在浏览器中是无法显示的,原因是这个文件的输出流被设置成了ImageFormat.Gif。要解决这个问题,只需创建一个新的页面,取名Test.aspx,然后加入这样的代码:
This is my p_w_picpath <BR> <img src="Image.aspx" />
Bitmap bmp = new Bitmap(300, 30); Graphics dc = Graphics.FromImage(bmp); Font f = new Font("Verdana", 11); dc.DrawString("[email]myemail@mydomainname.com[/email]", f, Brushes.Yellow, 0, 0); bmp.Save(Response.OutputStream, ImageFormat.Gif);
Test.aspx
Please email me at <BR /> <IMG src="Image.aspx" />
Random Rand = new Random(); // Create a new random number between the specified range int iNum= Rand.Next(10000, 99999); Bitmap Bmp = new Bitmap(90, 50); Graphics gfx = Graphics.FromImage(Bmp); Font fnt = new Font("Verdana", 12); // Draw the random number gfx.DrawString(RandNum.ToString(), fnt, Brushes.Yellow, 15, 15); Bmp.Save(Response.OutputStream, ImageFormat.Gif);
Random Rand = new Random(); int iNum = Rand.Next(10000, 99999); Bitmap Bmp = new Bitmap(90, 50); Graphics Gfx = Graphics.FromImage(Bmp); Font Fnt = new Font("Verdana", 12, FontStyle.Bold); Gfx.DrawString(iNum.ToString(), Fnt, Brushes.Yellow, 15, 15); // Create random numbers for the first line int RandY1 = Rand.Next(0, 50); int RandY2 = Rand.Next(0, 50); // Draw the first line Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2); // Create random numbers for the second line RandY1 = Rand.Next(0, 50); RandY2 = Rand.Next(0, 50); // Draw the second line Gfx.DrawLine(Pens.Yellow, 0, RandY1, 90, RandY2); Bmp.Save(Response.OutputStream, ImageFormat.Gif); Session["Number"] = iNum;