📄 checkimage.java
字号:
package test;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.sun.image.codec.jpeg.*;
import java.awt.image.*;
import java.awt.*;
import javax.imageio.ImageIO;
public class CheckImage extends HttpServlet {
ServletConfig config=null;
private int Rsize;
public void init(ServletConfig config)throws ServletException
{
super.init(config);
this.config=config;
String isize=config.getInitParameter("Rsize");
Rsize=Integer.parseInt(isize);
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("image/jpeg;charset=GBK");
HttpSession session=request.getSession(true);
try{
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
// 创建图象的宽和高
int width=15*Rsize;
int height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
//创建随机对象
Random random = new Random();
// 设置背景色
g.setColor(getRandomColor(200,250));
g.fillRect(0, 0, width, height);
// 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandomColor(160,200));
for (int i=0;i<155;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x,y,x+xl,y+yl);
}
//设定字体
Font ff=new Font("Monotype Corsiva",Font.PLAIN,20);
g.setFont(ff);
// 随机产生的认证码(每次产生一位)
String sRand="";
for (int i=0;i<Rsize;i++)
{
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
// 设置各数位的颜色
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
g.drawString(rand,14*i+6,17);
}
session.setAttribute("rand",sRand);
g.dispose();// 图象生效
// 输出图象到页面
ImageIO.write(image, "JPEG", response.getOutputStream());
}
catch(Exception e)
{
PrintWriter out = response.getWriter();
out.print(e.toString());
}
}
//获取随机颜色
Color getRandomColor(int c1,int c2)
{
Random random = new Random();
if(c1>255)
c1=255;
if(c2>255)
c2=255;
int b1=c1+random.nextInt(c2-c1);
int b2=c1+random.nextInt(c2-c1);
int b3=c1+random.nextInt(c2-c1);
return new Color(b1,b2,b3);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
doGet(request,response);
}
public void destroy()
{
config=null;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -