<%@ page contenttype= "image/jpeg" import= "java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%>
<%!
Color getrandcolor (int fc,int BC) {//random color for a given 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);
}
%>
<%
Set Page Not Cached
Response.setheader ("Pragma", "no-cache");
Response.setheader ("Cache-control", "No-cache");
Response.setdateheader ("Expires", 0);
Create an image in memory
int width=60, height=20;
BufferedImage image = new BufferedImage (width, height, bufferedimage.type_int_rgb);
Get Graphics context
Graphics g = Image.getgraphics ();
Generate Random Class
Random random = new random ();
Set Background color
G.setcolor (Getrandcolor (200,250));
G.fillrect (0, 0, width, height);
Set font
G.setfont (New Font ("Times New Roman", font.plain,18));
Draw a border
G.setcolor (new color ());
G.drawrect (0,0,width-1,height-1);
//randomly generates 155 lines of interference to make the authentication code in the image difficult to detect by other programs
G.setcolor (Getrandcolor 160,200 ));
for (int i=0;i<155;i++)
{
int x = RANDOM.N Extint (width);
int y = random.nextint (height);
int xl = Random.nextint (12);
int yl = Random.nextint (12);
G.drawline (x,y,x+xl,y+yl);
}
Take a randomly generated authentication 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 in the image
G.setcolor (new color (20+random.nextint, 20+random.nextint (), 20+random.nextint (110));//Call function out of the same color, May be because the seed is too close, so can only be directly generated
g.DrawString (rand,13*i+6,16);
}
Save authentication Code in session
Session.setattribute ("Rand", Srand);