旋转的验证码

来源:互联网 发布:网络售彩何时恢复 编辑:程序博客网 时间:2024/05/22 05:08
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {


/**
* 在内存中生成图片,没有设置背景颜色,画填充矩形,并且和纸大小相同,矩形有颜色
* 获取笔的对象,设置颜色
* 先准备好数据,随机生成4个字符,把字符画到纸上
* 画干扰线
* 把内存中的图片输出到客户端上
*/

int width = 120;
int height = 30;

//在内存中生成图片
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

//获取画笔的对象
Graphics2D g = (Graphics2D) image.getGraphics();
//设置颜色
g.setColor(Color.GRAY);
//画填充矩形
g.fillRect(0, 0, width, height);
//设置颜色
g.setColor(Color.BLUE);
//画边框
g.drawRect(0, 0, width-1, height-1);
//准备数据,随机获取4个字符
String words = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM789561230";

//设置颜色
g.setColor(Color.YELLOW);
//设置字体
g.setFont(new Font("隶书",Font.BOLD,20));
Random random = new Random();


int x = 20;
int y = 20;
for(int i = 0; i < 4; i++){
/**
* Theta弧度
* 弧度 = 角度*Math.PI/180
* 获取正负30之间的角度
*/
int jiaodu = random.nextInt(60)-30;
double hudu = jiaodu*Math.PI/180;
g.rotate(hudu, x, y);
//获取下标
int index = random.nextInt(words.length());

char ch = words.charAt(index);
//写字符串
g.drawString(""+ch, x, y);
//返回到0位置转
g.rotate(-hudu, x, y);
x = x+20;
}
//设置颜色
g.setColor(Color.GREEN);
int x1, y1, x2, y2;
for(int i = 0; i < 4; i++){
//画干扰线
x1 = random.nextInt(width);
y1 = random.nextInt(height);
x2 = random.nextInt(width);
y2 = random.nextInt(height);
g.drawLine(x1, y1, x2, y2);
}


//把内存中的图片输出到浏览器端
ImageIO.write(image, "jpg", response.getOutputStream());






}
0 0