A new. cs file is used to write a method that generates a graphical verification code, returning a MemoryStream parameter. The output will be received in the Default.aspx.
1. The following is the code for. CS
Using system;using system.collections.generic;using system.linq;using system.web;using System.Drawing;using system.drawing.drawing2d;using system.drawing.imaging;using system.io;///<summary>///bitmapimage Summary description/// </summary>public class bitmapimage{public static MemoryStream Imagecheck () {Random random = new Rando M (); Randomly generates 4-bit random number string checkcode = random. Next (1000, 9999). ToString (); Bitmap is used to specify the size of the text at initialization Bitmap image = new Bitmap ((int) math.ceiling ((Checkcode.length * 20.5)), 22); Graphics g = graphics.fromimage (image); try {g.clear (color.white);//Empty picture background color//Picture background noise line here is 4 lines for (int i = 0; i < 4; I + +) {int x1 = random. Next (image. Width); int x2 = random. Next (image. Width); int y1 = random. Next (image. Height); int y2 = random. Next (image. Height); G.drawline (New Pen (Color.Black), X1, x2, y1, y2); } font font = new Font ("Arial", fontstyle.bold); Set the color, starting position and other parameters LinearGradientBrush brush = new LinearGradientBrush (new Rectangle (0, 0, image. Width, image. Height), Color.Blue, color.darkred, 1.2f, true); g.DrawString (Checkcode, Font, brush, 2, 2); Picture the foreground noise point for (int i = 0; i < i++) {int x = random. Next (image. Width); int y = random. Next (image. Height); Image. SetPixel (x, Y, Color.FromArgb (random. Next ())); }//Draw picture Noise line G.drawrectangle (new Pen (Color.silver), 0, 0, image. Width-1, image. HEIGHT-1); MemoryStream ms = new MemoryStream (); Image. Save (MS, Imageformat.gif); return MS; } finally {g.dispose (); Image. Dispose (); } }}
2. The following is the code in Default.aspx.cs
Using system;using system.collections.generic;using system.linq;using system.web;using System.Web.UI;using System.web.ui.webcontrols;using system.io;public Partial class _default:system.web.ui.page{ protected void Page_ Load (object sender, EventArgs e) { MemoryStream ms= bitmapimage.imagecheck (); Response.clearcontent (); Response.ContentType = "Image/gif"; Response.BinaryWrite (Ms. ToArray ());} }
3.
Graphics Verification Code