[java]代码库
package a;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class VerifyCode extends HttpServlet {
private final int width = 120;
private final int height = 30;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics2D g = (Graphics2D) img.getGraphics();
g.setColor(Color.white);
g.fillRect(0, 0, width, height);
g.setColor(Color.blue);
g.drawRect(0, 0, width-1, height-1);
String base = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random ran = new Random();
g.setFont(new Font("宋体",Font.BOLD,20));
int x = 0, y = 20;
String value="";
for(int i = 1; i<=4; i++){
int index = ran.nextInt(base.length());
char ch = base.charAt(index);
int degree = ran.nextInt(60) -30;
double theta = degree*Math.PI;
g.rotate(theta, x+20*i, 15);
g.drawString(ch+"", x+20*i, y);
g.rotate(-theta, x+20*i,15);
value+=ch;
}
request.getSession().setAttribute("value",value);
g.setColor(Color.yellow);
int x1,y1,x2,y2;
for(int i = 1; i<=5; i++){
x1 = ran.nextInt(width);
y1 = ran.nextInt(height);
x2 = ran.nextInt(width);
y2 = ran.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}
g.dispose();
ImageIO.write(img, "jpg", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
[代码运行效果截图]
[源代码打包下载]