package com.hygj.servlet;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
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 TestResponse extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int width = 50;//设置宽
int height = 20;//设置高
//设置MIME类型为图片
response.setContentType("image/jpeg");
//得到输入输出流
OutputStream output = response.getOutputStream();
//成生图片缓存 参数:图片的宽,高,类型(RGB)
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//得到图片生成对象
Graphics gs = image.getGraphics();
//设置背景色
gs.setColor(Color.white);
//生成图片,并约定图片大小
gs.fillRect(0, 0, width, height);
//设置字体 参数:字体类型,字体样式,字体大小
gs.setFont(new Font("黑体",Font.BOLD,14));
//字体色的数组
Color[] col = new Color[10];
col[0] = Color.blue;
col[1] = Color.cyan;
col[2] = Color.green;
col[3] = Color.orange;
col[4] = new Color(198,143,6);
col[5] = new Color(5,4,200);
col[6] = new Color(63,49,172);
col[7] = new Color(16,234,78);
col[8] = new Color(100,0,200);
col[9] = new Color(119,110,120);
//随机数
Random ran = new Random();
for(int i = 0 ; i < 4 ; i++){
//设置随机数的色
gs.setColor(col[ran.nextInt(10)]);
//将数字画到图片上
gs.drawString(String.valueOf(ran.nextInt(10)), 9*(i+1), 14);
//画线
gs.drawLine(ran.nextInt(10)*5, ran.nextInt(10)*2, ran.nextInt(10)*6, ran.nextInt(10)*5);
}
//清空gs缓存
gs.dispose();
//输出图片
ImageIO.write(image, "jpeg", output);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}