public static final int WIDTH=125;
public static final int HEIGHT=35;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
setBackGround(g);//1.设置背景
setBorder(g); //2.设置边框
drawRandomLine(g);//3.设置随机线
drawRandomNum((Graphics2D)g);//4.设置随机数
response.setContentType("image/jpeg");
ImageIO.write(image, "jpg", response.getOutputStream()); //5。设置浏览器的显示
}
private void setBackGround(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
private void setBorder(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(1, 1, WIDTH-2, HEIGHT-2);
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.GREEN);
for(int i=0;i<4;i++){
int x1=new Random().nextInt(WIDTH);
int y1=new Random().nextInt(HEIGHT);
int x2=new Random().nextInt(WIDTH);
int y2=new Random().nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
}
private void drawRandomNum(Graphics2D g) {
g.setColor(Color.red);
g.setFont(new Font("宋体",Font.BOLD,20));
int x=10;
for(int i=0;i<4;i++){
int degree=new Random().nextInt()%30;
int num=new Random().nextInt(10);
String s=num+"";
g.rotate(degree*Math.PI/180, x, HEIGHT-9);//设置旋转的角度
g.drawString(s, x, HEIGHT-9);
g.rotate(-degree*Math.PI/180, x, HEIGHT-9);
x+=30;
}
}
public static final int HEIGHT=35;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
setBackGround(g);//1.设置背景
setBorder(g); //2.设置边框
drawRandomLine(g);//3.设置随机线
drawRandomNum((Graphics2D)g);//4.设置随机数
response.setContentType("image/jpeg");
ImageIO.write(image, "jpg", response.getOutputStream()); //5。设置浏览器的显示
}
private void setBackGround(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
private void setBorder(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(1, 1, WIDTH-2, HEIGHT-2);
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.GREEN);
for(int i=0;i<4;i++){
int x1=new Random().nextInt(WIDTH);
int y1=new Random().nextInt(HEIGHT);
int x2=new Random().nextInt(WIDTH);
int y2=new Random().nextInt(HEIGHT);
g.drawLine(x1, y1, x2, y2);
}
}
private void drawRandomNum(Graphics2D g) {
g.setColor(Color.red);
g.setFont(new Font("宋体",Font.BOLD,20));
int x=10;
for(int i=0;i<4;i++){
int degree=new Random().nextInt()%30;
int num=new Random().nextInt(10);
String s=num+"";
g.rotate(degree*Math.PI/180, x, HEIGHT-9);//设置旋转的角度
g.drawString(s, x, HEIGHT-9);
g.rotate(-degree*Math.PI/180, x, HEIGHT-9);
x+=30;
}
}