Dynamic generation of image page dycreateimage. aspx
Using system. Drawing. imaging;
Using system. Drawing. drawing2d;
Using system. drawing;
Protected void page_load (Object sender, eventargs E)
{
Generaterandomimage (checkcode ());
}
Private string checkcode ()
{
String checkcode = string. empty;
Random Rand = new random ();
Int temp;
For (INT I = 0; I <4; I ++)
{
Temp = Rand. Next (48, 57 );
Checkcode + = (char) temp). tostring ();
}
Response. Cookies. Add (New httpcookie ("checkcode", checkcode ));
Return checkcode;
}
Private void generaterandomimage (string S)
{
If (S = NULL | S. Trim () = string. Empty)
Return;
Int iwidth = (INT) math. Ceiling (S. length * 15 m );
Int iheight = 20;
Bitmap IMG = new Bitmap (iwidth, iheight );
Graphics G = graphics. fromimage (IMG );
G. Clear (color. White );
Try
{
Random Rand = new random ();
For (INT I = 0; I <20; I ++)
{
Int X1 = Rand. Next (iwidth );
Int Y1 = Rand. Next (iheight );
Int X2 = Rand. Next (iwidth );
Int y2 = Rand. Next (iheight );
G. drawline (new pen (brushes. Silver), X1, Y1, X2, Y2 );
}
For (INT I = 0; I <50; I ++)
{
Int X1 = Rand. Next (iwidth );
Int Y1 = Rand. Next (iheight );
IMG. setpixel (x1, Y1, color. fromargb (RAND. Next ()));
}
G. drawrectangle (new pen (color. saddlebrown), 0, 0, iwidth-1, iheight-1 );
Font font = new font ("arail", 14, fontstyle. Bold );
Lineargradientbrush LGB = new lineargradientbrush (New rectangle (0, 0, iwidth, iheight), color. Blue, color. Purple, lineargradientmode. Horizontal );
G. drawstring (S, Font, LGB, 1, 0 );
Using (memorystream MS = new memorystream ())
{
IMG. Save (MS, imageformat. PNG );
Response. Clear ();
Response. contenttype = "image/PNG ";
Response. binarywrite (Ms. toarray ());
Response. End ();
}
}
Finally
{
G. Dispose ();
IMG. Dispose ();
}
}
Call the HTML code at the front end of the page:
<Tr>
<TD align = "Middle" Height = "28">
Verification Code:
</TD>
& Lt; TD width = "27%" & gt;
<Input class = "input_yz" id = "_ txtcode" runat = "server"/>
</TD>
& Lt; TD width = "46%" & gt;
Height = "19" alt = "Verification Code"/>
</TD>
</Tr>
Function changeimage ()
{
Document. getelementbyid ("imgrandom"). src = Document. getelementbyid ("imgrandom"). SRC + "? ";
}