package com.xpwj.action;
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.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ss extends HttpServlet {
//生成随机颜色
Color getRandColor(Random random,int fc,int bc)
{
if(fc>255) fc=255;
if(bc>255) bc=255;
int r=fc+random.nextInt(bc-fc);
int g=fc+random.nextInt(bc-fc);
int b=fc+random.nextInt(bc-fc);
return new Color(r,g,b);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession(true);
response.setContentType("image/jpeg");
//设置页面不缓存
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
// 设置图片的长宽
int width=176, height=30;
//创建内存图像
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 获取图形上下文
Graphics g = image.getGraphics();
//创建随机类的实例
Random random = new Random();
// 设定图像背景色(因为是做背景,所以偏淡)
g.setColor(getRandColor(random,200,250));
g.fillRect(0, 0, width, height);
//备选字体
String[] fontTypes = {"\u5b8b\u4f53","\u65b0\u5b8b\u4f53","\u9ed1\u4f53","\u6977\u4f53","\u96b6\u4e66"};
int fontTypesLength = fontTypes.length;
//在图片背景上增加噪点
g.setColor(getRandColor(random,160,200));
g.setFont(new Font("Times New Roman",Font.PLAIN,14));
for (int i=0;i<6;i++)
{
g.drawString("*********************************************",0,5*(i+2));
}
//取随机产生的认证码(6个汉字)
String[] ys=new String[]{"零","壹","贰","叁","肆","伍","陸","柒","捌","玖","拾"};
//保存生成的汉字字符串
String sRand="";
int ys1=random.nextInt(10);
int ys2=random.nextInt(10);
String[] ysfs=new String[]{"加","减","乘"};
String[] ysfs2=new String[]{"+","-","*"};
int ysfIndex = random.nextInt(ysfs.length);
int index = random.nextInt(2);
int ysindex = random.nextInt(2);
String ysf = "";
String ys1s=ys1+"";
String ys2s=ys2+"";
//随机运算数
switch (index) {
case 0:
ys1s=ys[ys1];
break;
case 1:
ys2s=ys[ys2];
break;
}
//随机运算符
switch (ysindex) {
case 0:
ysf = ysfs[ysfIndex];
break;
case 1:
ysf = ysfs2[ysfIndex];
break;
}
int val = 0;
switch (ysfIndex) {
case 0:
val = ys1 + ys2;
break;
case 1:
val = ys1 - ys2;
break;
case 2:
val = ys1 * ys2;
break;
default:
break;
}
sRand=ys1s+ysf+ys2s+"=?";
//设置字体的颜色
g.setColor(getRandColor(random,10,150));
//设置字体
g.setFont(new Font(fontTypes[random.nextInt(fontTypesLength)],Font.BOLD,18 + random.nextInt(6)));
//将此汉字画到图片上
g.drawString(sRand,24*0+ 10 + random.nextInt(8),24);
//将认证码存入session
session.setAttribute("ss",String.valueOf(val));
g.dispose();
//输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}