1 package com.response; 2 3 import java.awt.Color; 4 import java.awt.Font; 5 import java.awt.Graphics; 6 import java.awt.Graphics2D; 7 import java.awt.image.BufferedImage; 8 import java.io.IOException; 9 import java.io.PrintWriter; 10 import java.util.Random; 11 12 import javax.imageio.ImageIO; 13 import javax.servlet.ServletException; 14 import javax.servlet.http.HttpServlet; 15 import javax.servlet.http.HttpServletRequest; 16 import javax.servlet.http.HttpServletResponse; 17 18 public class Demo2 extends HttpServlet { 19 20 public static final int WIDTH=120;//设置图像的宽 21 public static final int HEIGHT=25;//设置图像的高 22 public void doGet(HttpServletRequest request, HttpServletResponse response) 23 throws ServletException, IOException { 24 this.doPost(request, response); 25 } 26 //输出注册时候的随机图片 27 public void doPost(HttpServletRequest request, HttpServletResponse response) 28 throws ServletException, IOException { 29 //BufferedImage 可以自动生成图像,BufferedImage.TYPE_INT_RGB是图片的类型 30 BufferedImage image=new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); 31 //得到这个图形 32 Graphics g=image.getGraphics(); 33 34 //1.设置图像的背景色 35 setBackaground(g); 36 //2.设置图像的边框 37 setBorder(g); 38 //3.在图像上画干扰线 39 drawRandomLine(g); 40 //4.在图像上写随机数 41 drawRanderNum((Graphics2D)g); 42 //5.把图像写给浏览器,设置浏览器打开文件的格式 43 response.setContentType("image/jpeg"); 44 //发响应头控制浏览器不要缓存 45 response.setDateHeader("expries", -1); 46 response.setHeader("Cache-Control","no-cache"); 47 response.setHeader("Pragma","no-cache"); 48 ImageIO.write(image, "jpg", response.getOutputStream()); 49 50 } 51 private void drawRanderNum(Graphics2D g) { 52 g.setColor(Color.RED);//设置字的颜色为红色 53 g.setFont(new Font("宋体",Font.BOLD,20));//设置字体的样式,Font.BOLD为加粗,20字体的高度 54 int x=10; 55 for(int i=0;i<4;i++) 56 { 57 int degree=new Random().nextInt()%30;//定义字符旋转多少度,%30是表示度数为-30到30度 58 String shu=new Random().nextInt(10)+""; 59 g.rotate(degree*Math.PI/180, x, 20);//设置旋转的弧度,后两个参数是基于那个点旋转 60 g.drawString(shu , x, 20);//这是往图片上写入数字,参数是写入数字的坐标 61 g.rotate(-degree*Math.PI/180, x, 20);//清掉上次的旋转,确保下次的旋转正确 62 x=x+30; 63 } 64 65 } 66 private void drawRandomLine(Graphics g) { 67 g.setColor(Color.GREEN);//设置干扰线的颜色 68 for(int i=0;i<5;i++)//i为干扰线的条数 69 { 70 int x1=new Random().nextInt(WIDTH);//x1,y1为干扰线的起点的坐标,x坐标必须在图像的宽内,y坐标在高之内 71 int y1=new Random().nextInt(HEIGHT); 72 73 int x2=new Random().nextInt(WIDTH); 74 int y2=new Random().nextInt(HEIGHT); 75 g.drawLine(x1, y1, x2, y2);//这个方法是画出干扰线 76 } 77 78 } 79 private void setBorder(Graphics g) { 80 g.setColor(Color.BLUE);//?这里为什么只变的是边框 81 g.drawRect(1, 1, WIDTH-2, HEIGHT-2); 82 83 } 84 private void setBackaground(Graphics g) { 85 g.setColor(Color.WHITE);//设置图形的背景色为白色 86 g.fillRect(0, 0, WIDTH, HEIGHT);//填充矩形 87 88 } 89 90 }
//1.设置图像的背景色
setBackaground(g);
//2.设置图像的边框
setBorder(g);
//3.在图像上画干扰线
drawRandomLine(g);
//4.在图像上写随机数
drawRanderNum((Graphics2D)g);
这些方法都是自己写的,每个方法里面都有g.setColor(Color.RED);设置颜色的方法,程序是怎么知道我是想设置字体颜色,还是图像的颜色,还是边框,干扰线呢?