1.java代码如下:
package com.ask.session;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
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;
/**
* 输出一张随机图片 看jdk api 的bufferedImage类
*/
public class Demo4 extends HttpServlet {
public static final int WIDTH=120;
public static final int HEIGHT=30;
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
//构建一张图
BufferedImage image=new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
//创建图形上下文
Graphics g=image.getGraphics();
//设置背景色
setBackgroundColor(g);
//设置边框
// setBorder(g);
//画干扰线
drawRandomLine(g);
//写随机数
drawRandomNumber((Graphics2D)g);
//图形输出到浏览器
res.setContentType("image/jpeg");
ImageIO.write(image, "jpg", res.getOutputStream());
}
private void drawRandomNumber(Graphics2D g) {
//汉字区间:\u4100~\u9fa5
String base="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String number="";
g.setColor(Color.BLUE);
g.setFont(new Font("宋体", Font.BOLD,25));
int x=10;
for (int i = 0; i < 4; i++) {
//定义的旋转弧度30到-30的角度
int degree=new Random().nextInt()%30;
number=base.charAt(new Random().nextInt(base.length()))+"";
//让字体旋转30度
g.rotate(degree*Math.PI/180, x, 20);
g.drawString(number, x, 23);
//清楚旋转度数
g.rotate(-degree*Math.PI/180, x,20);
x+=30;
}
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.gray);
for (int i = 0; i < 8; 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 setBorder(Graphics g) {
g.setColor(Color.BLUE);
g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
}
private void setBackgroundColor(Graphics g) {
g.setColor(Color.white);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
}
2.web.xml配置文件如下:
<!--随机验证码 -->
<servlet>
<servlet-name>demo4</servlet-name>
<servlet-class>com.ask.session.Demo4</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo4</servlet-name>
<url-pattern>/demo4</url-pattern>
</servlet-mapping>