import java.io.IOException;
import java.io.PrintWriter;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class ImageServlet 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 char[] getRand() {
char[] rand = new char[4];
String str = "0123456789qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM";
for (int i = 0; i < 4; i++) {
Random rd = new Random();
int index = rd.nextInt(str.length());
// 通过下标获取字符
rand[i] = str.charAt(index);
}
return rand;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接收图片类型
response.setContentType("image/jepg");
// 创建字节流
ServletOutputStream sos = response.getOutputStream();
// 设置缓冲区
BufferedImage img = null;
img=new BufferedImage(60, 25, 4);
// 在缓冲区中绘图
Graphics g = img.getGraphics();
// 调方法,得到随机字符
char[] rand = this.getRand();
// 保存于session中,以便其它页面可用
request.getSession().setAttribute("rand", new String(rand));
// 干拢线
g.setColor(Color.red);
g.drawLine(new Random().nextInt(60), new Random().nextInt(60),
new Random().nextInt(20), new Random().nextInt(20));
g.drawLine(new Random().nextInt(60), new Random().nextInt(60),
new Random().nextInt(60), new Random().nextInt(20));
g.drawLine(new Random().nextInt(80), new Random().nextInt(60),
new Random().nextInt(50), new Random().nextInt(20));
// 画背景色
g.drawRect(0, 0, 60, 25);
g.setColor(Color.blue);
// 设置前景色
g.setColor(Color.green);
g.setFont(new Font("宋体",Font.BOLD+Font.ITALIC,18));//设置字体
g.drawString("" + rand[0], 6, 20);
g.drawString("" + rand[1], 20, 15);
g.drawString("" + rand[2], 30, 15);
g.drawString("" + rand[3], 50, 20);
// 关闭
g.dispose();
//JPEGImageEncoder code = JPEGCodec.createJPEGEncoder(sos);
//code.encode(img);
ImageIO.write((BufferedImage) img, "JPEG", sos);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}