& Lt % @ page contentType = "image/jpeg"
Import = "java. awt .*,
Java. awt. image .*,
Java. util .*,
Javax. imageio .*"
% & Gt
& Lt %
// Create an image in memory
Int width = 60, height = 20;
BufferedImage image = new BufferedImage (width, height,
BufferedImage. TYPE_INT_RGB );
// Obtain the image Context
Graphics g = image. getGraphics ();
// Set the background color
G. setColor (new Color (0 xDCDCDC ));
G. fillRect (0, 0, width, height );
// Draw a border
G. setColor (Color. black );
G. drawRect (0, 0, width-1, height-1 );
// Obtain the random ID code (4 digits)
String rand = request. getParameter ("rand ");
Rand = rand. substring (0, rand. indexOf ("."));
Switch (rand. length ())
{
Case 1: rand = "000" + rand; break;
Case 2: rand = "00" + rand; break;
Case 3: rand = "0" + rand; break;
Default: rand = rand. substring (0, 4); break;
}
// Save the authentication code to the SESSION
Session. setAttribute ("rand", rand );
// Display the authentication code to the image
G. setColor (Color. black );
Integer tempNumber = new Integer (rand );
String numberStr = tempNumber. toString ();
G. setFont (new Font ("Atlanta Inline", Font. PLAIN, 18 ));
String Str = numberStr. substring (0, 1 );
G. drawString (Str, 8, 17 );
Str = numberStr. substring (1, 2 );
G. drawString (Str, 20, 15 );
Str = numberStr. substring (2, 3 );
G. drawString (Str, 35, 18 );
Str = numberStr. substring (3, 4 );
G. drawString (Str, 45, 15 );
// 88 random interference points are generated, making the authentication code in the image hard to be detected by other programs.
Random random = new Random ();
For (int I = 0; I & lt 20; I ++)
{
Int x = random. nextInt (width );
Int y = random. nextInt (height );
G. drawOval (x, y, 0, 0 );
}
// The image takes effect
G. dispose ();
// Output the image to the page
ImageIO. write (image, "JPEG", response. getOutputStream ());
% & Gt