Image verification is often used for registration and posting. I wrote one here using jsp. for your reference. com. sun. image is not a java standard package. additional download is required. address related: http://java.sun.com/products/java-media/jai/
1. random. jsp (generate four random characters, consisting of 0-9, a-z, A-Z. And put the final string in the session to save for subsequent page verification authenticity)
The Code is as follows:
<% @ Page autoFlush = "false" import = "java. util. *, java. awt. *, java. awt. image. *, com.sun.image.codec.jpeg. *, java. util. * "%>
<% @ Page import = "" contentType = "text/html; charset = gb2312" %>
<%
String chose = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";
Char display [] = {'0', '', '0','', '0', '', '0 '}, ran [] = {'0', '0', '0', '0'}, temp;
Random rand = new Random ();
For (int I = 0; I <4; I ++)
{
Temp = chose. charAt (rand. nextInt (chose. length ()));
Display [I * 2] = temp;
Ran [I] = temp;
}
String random = String. valueOf (display );
Session. setAttribute ("random", String. valueOf (ran ));
%>
<%
Out. clear ();
Response. setContentType ("image/jpeg ");
Response. addHeader ("pragma", "NO-cache ");
Response. addHeader ("Cache-Control", "no-cache ");
Response. addDateHeader ("Expries", 0 );
Int width = 47, height = 15;
BufferedImage image = new BufferedImage (width, height, BufferedImage. TYPE_INT_RGB );
Graphics g = image. getGraphics ();
// Fill in the background color below
G. setColor (Color. GREEN );
G. fillRect (0, 0, width, height );
// Set the font color
G. setColor (Color. RED );
G. drawString (random, 3,10 );
G. dispose ();
ServletOutputStream outStream = response. getOutputStream ();
Required imageencoder encoder = required codec. createJPEGEncoder (outStream );
Encoder. encode (image );
OutStream. close ();
%>
2. img. jsp (the verification image is displayed. The verification program is also put together due to the simplicity of this Program)
The Code is as follows:
<% @ Page contentType = "text/html; charset = gb2312" language = "java" %>
<%
String num = request. getParameter ("num ");
String random = (String) session. getAttribute ("random ");
If (num! = Null & random! = Null)
{
If (! Num. equals (random ))
{
Out. println ("<script> alert ('verification code error! Please try again. ') </Script> ");
Out. println ("<script> history. go (-1) </script> ");
// Response. sendRedirect ("img. jsp ");
}
Else
{
Out. println ("<center> Verification Successful! </Center> ");
}
}
%>
<Html>
<Head>
<Title> image verification </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
</Head>
<Body>
<Form action = "img. jsp" method = "post">
<Table>
<Tr>
<Td>
<Input type = "text" name = "num" size = 10>
</Td>
<Td>
</Td>
</Tr>
</Table>
<Input type = "submit" value = "OK">
</Form>
</Body>
</Html>