- package com.response;
- 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.io.PrintWriter;
- 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 Demo2 extends HttpServlet {
- public static final int WIDTH=120;//设置图像的宽
- public static final int HEIGHT=25;//设置图像的高
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doPost(request, response);
- }
- //输出注册时候的随机图片
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //BufferedImage 可以自动生成图像,BufferedImage.TYPE_INT_RGB是图片的类型
- BufferedImage image=new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
- //得到这个图形
- Graphics g=image.getGraphics();
-
- //1.设置图像的背景色
- setBackaground(g);
- //2.设置图像的边框
- setBorder(g);
- //3.在图像上画干扰线
- drawRandomLine(g);
- //4.在图像上写随机数
- drawRanderNum((Graphics2D)g);
- //5.把图像写给浏览器,设置浏览器打开文件的格式
- response.setContentType("image/jpeg");
- //发响应头控制浏览器不要缓存
- response.setDateHeader("expries", -1);
- response.setHeader("Cache-Control","no-cache");
- response.setHeader("Pragma","no-cache");
- ImageIO.write(image, "jpg", response.getOutputStream());
- }
- private void drawRanderNum(Graphics2D g) {
- g.setColor(Color.RED);//设置字的颜色为红色
- g.setFont(new Font("宋体",Font.BOLD,20));//设置字体的样式,Font.BOLD为加粗,20字体的高度
- int x=10;
- for(int i=0;i<4;i++)
- {
- int degree=new Random().nextInt()%30;//定义字符旋转多少度,%30是表示度数为-30到30度
- String shu=new Random().nextInt(10)+"";
- g.rotate(degree*Math.PI/180, x, 20);//设置旋转的弧度,后两个参数是基于那个点旋转
- g.drawString(shu , x, 20);//这是往图片上写入数字,参数是写入数字的坐标
- g.rotate(-degree*Math.PI/180, x, 20);//清掉上次的旋转,确保下次的旋转正确
- x=x+30;
- }
-
- }
- private void drawRandomLine(Graphics g) {
- g.setColor(Color.GREEN);//设置干扰线的颜色
- for(int i=0;i<5;i++)//i为干扰线的条数
- {
- int x1=new Random().nextInt(WIDTH);//x1,y1为干扰线的起点的坐标,x坐标必须在图像的宽内,y坐标在高之内
- 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 setBackaground(Graphics g) {
- g.setColor(Color.WHITE);//设置图形的背景色为白色
- g.fillRect(0, 0, WIDTH, HEIGHT);//填充矩形
-
- }
- }
复制代码
代码刚忘记提交了 |