importar java.awt.Color;
importar java.awt.Font;
importar java.awt.Graphics;
importar java.awt.Graphics2D;
importar java.awt.image.BufferedImage;
importar java.io.IOException;
importar java.util.Random;
importar javax.imageio.ImageIO;
importar javax.servlet.ServletException;
importar javax.servlet.http.HttpServlet;
importar javax.servlet.http.HttpServletRequest;
importar javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
classe pública ValidatePicture estende HttpServlet {
public void doGet (solicitação HttpServletRequest, resposta HttpServletResponse)
lança ServletException, IOException {
tentar {
validar imagem(solicitação, resposta);
} catch (Exceção e) {
e.printStackTrace();
}
}
public void doPost (solicitação HttpServletRequest, resposta HttpServletResponse)
lança ServletException, IOException {
doGet(solicitação,resposta);
}
público estático final int WIDTH = 120;
público estático final int ALTURA = 25;
imagem de validação pública void (solicitação HttpServletRequest,
Resposta HttpServletResponse) lança Exception {
BufferedImage bi = novo BufferedImage(LARGURA, ALTURA,
BufferedImage.TYPE_INT_RGB);// 在内存中构建一幅图象
Gráficos g = bi.getGraphics();
setBackGround(g);// 设置背景色
setBorder(g);// 设置边框
drawRandomLine(g);// 画干扰线
String random = drawRandomNum((Graphics2D) g);// Resultado
request.getSession().setAttribute("aleatório", aleatório);
//request.getSession(false);
resposta.setContentType("imagem/jpeg");
// 设置不要缓存
resposta.setDateHeader("expries", -1);
response.setHeader("Cache-Control", "sem cache");
ImageIO.write(bi, "jpg", resposta.getOutputStream());
}
private String drawRandomNum(Graphics2D g) {
g.setColor(Color.RED);
g.setFont(new Font("宋体", Font.BOLD, 20));
// [/u4e00-/u9fa5]中文数字区间
String base = "/u4e00/u4f00/u5e00/u4e50/u4e89/u4f10/u4e09";
StringBuffer sb = new StringBuffer();
interno x = 5;
for (int i = 0; i < 4; i++) {
int grau = new Random().nextInt() % 30;
String ch = base.charAt(new Random().nextInt(base.length())) + "";
sb.append(ch);
g.rotate(grau * Math.PI / 180, x, 20);
g.drawString(ch, x, 20);
g.rotate(-grau * Math.PI / 180, x, 20);
x = x + 30;
}
System.out.println(sb.toString());
retornar sb.toString();
}
private void drawRandomLine(Gráficos g) {
g.setColor(Color.GREEN);
for (int i = 0; i < 3; 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 setBorder(Gráficos g) {
g.setColor(Color.BLUE);
g.drawRect(1, 1, LARGURA - 2, ALTURA - 2);
}
private void setBackGround(Gráficos g) {
g.setColor(Cor.BRANCO);
g.fillRect(0, 0, LARGURA, ALTURA);
}
}