public class BufferedImageDemo extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int WIDTH = 120;
private static final int HEIGHT = 35;
protected 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);
//设置边框
setBorder(g);
//生成线条
dawRandomLine(g);
//生成汉字
dawRandomNum((Graphics2D)g);
//设置头 告诉浏览器以哪种格式显示数据
response.setContentType("image/jpeg");
//将图片写到页面
ImageIO.write(image, "jpg", response.getOutputStream());
}
//设置图片背景颜色
private void setBackGround(Graphics g) {
//设置图片背景颜色为白色
g.setColor(Color.WHITE);
//填充图片
g.fillRect(0, 0, WIDTH, HEIGHT);
}
//设置边框
private void setBorder(Graphics g) {
//设置边框颜色
g.setColor(Color.BLUE);
//将线条画到图片上
g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
}
//生成随机线条
private void dawRandomLine(Graphics g) {
//设置线条颜色
g.setColor(Color.GREEN);
//随机位置生成五个线条
for(int i=0;i<5;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 dawRandomNum(Graphics2D g) throws IOException {
//设置汉字颜色
g.setColor(Color.BLACK);
//设置字体,大小,格式
g.setFont(new Font("宋体",Font.BOLD,20));
//读取配置文件中的常用汉字
String path = BufferedImageDemo.class.getClassLoader().getResource("chinese.properties").getPath();
InputStream is = new FileInputStream(path);
Properties p = new Properties();
p.load(is);
String base = p.getProperty("base");
int x= 5;
//生成4个汉字
for(int i=0;i<4;i++){
//随机生成汉字旋转角度 -30~+30之间
int degree = new Random().nextInt()%30;
//从常用汉字中随机找出一个汉字
String ch = base.charAt(new Random().nextInt(base.length()))+"";
//设置汉字旋转角度,这个方法只有Graphics2D中有
g.rotate(degree*Math.PI/180, x, 25);
//把汉字写到图片上
g.drawString(ch, x, 25);
//将角度恢复
g.rotate(-degree*Math.PI/180, x, 25);
//每个汉字之间隔30,再写下一个汉字
x+=30;
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}