语句的作用注释在代码块中
运行结果:
随机生成宽250,长150的验证码图片:
生成一张250X150的图片:
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//生成图片
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(generatePic(250,150),"JPEG" ,sos);
sos.flush();
sos.close();
}
先建立一张图片:
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) image.getGraphics();
width是图片宽度,height是图片长度,最后一个参数是图片类型。
新建一个类randString,能够获取随机字符:
public static String randString(int count){
String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";//字符串仓库
Random rand = new Random();
String res = "";
for(int i = 0;i<count;i++){
res +=text.charAt(rand.nextInt(text.length()));
}//通过循环语句,生成随机字符
return res;
}
然后在图片类中添加语句:
String text = CaptcheController.randString(4);//生成4个随机字符
for (int i = 0; i < text.length(); i++) {
Random rand = new Random();
g.setFont(new Font("宋体", Font.BOLD, randint((int) (width * 0.2), (int) (height * 0.6))));//设置字体,字号随着图片大小而改变
g.setColor(new Color(rand.nextInt(255), rand.nextInt(255), rand.nextInt(255)));//设置字体颜色,在0~255之间随机
AffineTransform aff = g.getTransform();
double radis = Math.toRadians(rand.nextInt(140));//设置字体的旋转角度,在0~140度之间随机
int x = (int) (width * 0.4); //字体的X坐标
int y = (int) (height * 0.5);//字体的Y坐标
g.rotate(radis, 125, 75);//旋转图片
g.drawString(text.charAt(i) + "", x, y);
}
新建一个类randint,用来固定字符串的位置:
public static int randint(int a,int b){
Random r = new Random();
int res = r.nextInt(b-a);
res += a ;
return res;
}
使用drawOval方法生成噪点,使用循环+随机坐标来生成:
for (int i = 0; i < 20; i++) {
Random r = new Random();
int x = r.nextInt(width);
int y = r.nextInt(height);
g.drawOval(x, y, 5, 5);
}
新建类getRandColor,设置线条:
private static 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(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
在图片类中添加设置线条语句:
Random r2 = new Random();
g.setColor(getRandColor(160,200));//设置线条颜色
for (int i=0;i<20;i++){
int x = r2.nextInt(width-20);//设置线条的宽度
int y = r2.nextInt(height-10);//设置线条高度
int xl = r2.nextInt(12);
nt yl = r2.nextInt(20);
g.drawLine(x,y,x+xl+30,y+yl+20);
}