Import java. Io .*;
Import java. util .*;
Import com.sun.image.codec.jpeg .*;
Import javax. servlet .*;
Import javax. servlet. http .*;
Import java. AWT .*;
Import java. AWT. image .*;
Public class showimage extends httpservlet {
Private font mfont = new font ("Times New Roman", Font. Plain, 18); // set the font
// Process post
Public void dopost (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Doget (request, response );
}
Public void doget (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
// Obtain a random number of 1000-9999
Httpsession session = request. getsession (false );
// Session. setattribute ("getimg", S );
Response. setcontenttype ("image/GIF ");
Response. setheader ("Pragma", "No-Cache ");
Response. setheader ("cache-control", "No-Cache ");
Response. setdateheader ("expires", 0 );
Int width = 60, Height = 20;
Servletoutputstream out = response. getoutputstream ();
Bufferedimage image = new bufferedimage (width, height, bufferedimage. type_int_rgb); // set the image size
Graphics gra = image. getgraphics ();
Random random = new random ();
Gra. setcolor (getrandcolor (200,250); // sets the background color.
Gra. fillrect (0, 0, width, height );
Gra. setcolor (color. Black); // you can specify the font color.
Gra. setfont (mfont );
/* Gra. setcolor (new color (0 ));
Gra. drawrect (0, 0, width-1, height-1 );*/
// Generates 155 random interference lines, making the authentication code in the image hard to be detected by other programs.
Gra. setcolor (getrandcolor (160,200 ));
For (INT I = 0; I <155; I ++)
{
Int x = random. nextint (width );
Int y = random. nextint (height );
Int XL = random. nextint (12 );
Int yl = random. nextint (12 );
Gra. drawline (X, Y, x + XL, Y + yl );
}
// Obtain the random ID code (4 digits)
String srand = "";
For (INT I = 0; I <4; I ++ ){
String Rand = string. valueof (random. nextint (10 ));
Srand + = rand;
// Display the authentication code to the image
Gra. setcolor (new color (20 + random. nextint (110), 20 + random. nextint (110), 20 + random. nextint (110); // The color from the call function is the same, probably because the seed is too close, so it can only be generated directly.
Gra. drawstring (RAND, 13 * I + 6, 16 );
}
// System. Out. println ("showimage =" + srand );
Session. setattribute ("getimg", srand );
Required imageencoder encoder = required codec. createjpegencoder (out );
Encoder. encode (image );
Out. Close ();
}
Static color getrandcolor (int fc, int BC) {// obtain the random color in the specified range
Random random = new random ();
If (FC> 255) fc = 255;
If (BC> 255) BC = 255;
Int r = FC + random. nextint (BC-Fc );
Int G = FC + random. nextint (BC-Fc );
Int B = FC + random. nextint (BC-Fc );
Return new color (R, G, B );
}
}