package com.bjsxt.controller;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.sql.rowset.serial.SerialException;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/codeServlet")
class CodeServlet extends HttpServlet{
@override
protected void service(HttpServletRequest req,HttpServletResponse resp)throws SerialException, IOException {
//在内存中创建图像
int width = 110,height = 30;
BufferedImage image = new BufferedImage(width,herght,BufferedImage,TYPE_INT_RGB);
//获取图像上下文
Graphics g = image.getGraphics();
//设置背景色
g.setColor(getRandColor(fc:200,bc:250));
g.fillRect(x:0,y:0,width,height);
//设定字体
g.setFont(new Font(name:"Times New Roman", Font.PLAIN,size:20));
//随机产生155条干扰线,使图像中的认证码不易被其他软件检测到
g.setColor(getRandColor(fc:160,bc:200));
for(int i=0;i<155;i++){
int x = randdom.nextInt(width);
int y = randdom.nextInt(height);
int x1 = randdom.nextInt(12);
int y1 = randdom.nextInt(12);
g.drawLine(x,y,x2:x+x1,y2:y+y1);
}
//随机产生的认证码(6位数字)
String sRand = "";
for(int i = 0;i<6;i++){
String rand = String.valueOf(randm.nextInt(10));
sRand+=rand;
//将认证码显示到图像中
g.setColor(new Color(20 + random.nextInt(100),20 + rand.nexInt(110),20 + rand.nextInt(110)));
//调用函数出来的颜色相同,可能使因为种子台接近,所以只能之间生成
g.drawString(rand,13 * i +6,16);
}
//图像生成
g.dispose();
try{
InmageIO.write(image,image,"JPEG",response.getOutputStream());
}catch(Exception e){
System.out.println("验证码图片产生出现错误:"+e.toString());
}
//保存验证码到Session
req.getSession().setAttribute("randStr",sRand);
}
/*
给定范围获得随机颜色
*/
private Color getRandColor(int fc,int bc){
Random random = new Random();
if(fc > 255)
fc = 255;
if(bc >255)
bc = 255;
int r = fc + random.nextInt(bound:bc - fc);
int g = fc + random.nextInt(bound:bc - fc);
int b = fc + random.nextInt(bound:bc - fc);
return new Color(r,g,b);
}
}
OA系统--给定范围随机颜色
最新推荐文章于 2022-12-09 20:49:15 发布