<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
Using System; using System. web; using System. drawing; using System. drawing. drawing2D; using System. web. sessionState; public class WaterMark: IHttpHandler, IRequiresSessionState // You must implement this interface to use session. Remember to import System. web. sessionState namespace {public void ProcessRequest (HttpContext context) {string checkCode = GenCode (5); // generates a five-character random context. session ["Code"] = checkCode; // Save the string to the Session so that System can be verified as needed. drawing. bitmap image = new System. drawing. bitmap (70, 22); Graphics g = Graphics. fromImage (image); try {// generate Random generator random Random = new Random (); // clear the image background color g. clear (Color. white); // specifies the background noise line of the image. int I; for (I = 0; I <25; 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. silver), x1, y1, x2, y2);} Font font = new System. drawing. font ("Arial", 12, (System. drawing. fontStyle. bold); System. drawing. drawing2D. linearGradientBrush brush = new System. drawing. drawing2D. linearGradientBrush (new Rectangle (0, 0, image. width, image. height), Color. blue, Color. darkRed, 1.2F, true); g. drawString (checkCode, font, brush, 2, 2); // The foreground noise of the picture. g. drawRectangle (new Pen (Color. silver), 0, 0, image. width-1, image. height-1); System. IO. memoryStream MS = new System. IO. memoryStream (); image. save (MS, System. drawing. imaging. imageFormat. gif); context. response. clearContent (); context. response. contentType = "image/Gif"; context. response. binaryWrite (ms. toArray ();} finally {g. dispose (); image. dispose ();}} /// <summary> /// generate a random string /// </summary> /// <param name = "num"> random output of several characters </param> // /<returns> random string </returns> private string GenCode (int num) {string str = "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ"; char [] chastr = str. toCharArray (); // string [] source = {"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 code = ""; Random rd = new Random (); int I; for (I = 0; I <num; I ++) {// code + = source [rd. next (0, source. length)]; code + = str. substring (rd. next (0, str. length), 1) ;}return code ;}public bool IsReusable {get {return false ;}}}