验证中...
助力高校计算机教育 —— 码云为老师推出免费高校版,高达 200 人的协作团队
语言: Java
分类: Web开发技术
最后更新于 2018-06-14 16:50
验证码工具类
原始数据 复制代码
package com.fasten.monitor.util;
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.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ImageUtil {
public static class VCode {
private static int width = 80;
private static int height = 20;
private static int codeCount = 4;
private static int xx = 15;
private static int fontHeight = 18;
private static int codeY = 16;
private static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9' };
public final static void generateCodeImg(HttpServletRequest request , HttpServletResponse response) throws IOException {
BufferedImage buffImg = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics gd = buffImg.getGraphics();
Random random = new Random();
gd.setColor(Color.WHITE);
gd.fillRect(0, 0, width, height);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
gd.setFont(font);
gd.setColor(Color.BLACK);
gd.drawRect(0, 0, width - 1, height - 1);
// 随机产生20条干扰线
gd.setColor(Color.BLACK);
for (int i = 0; i < 20; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
gd.drawLine(x, y, x + xl, y + yl);
}
StringBuffer randomCode = new StringBuffer();
int red = 0, green = 0, blue = 0;
// 随机产生验证码
for (int i = 0; i < codeCount; i++) {
String code = String.valueOf(codeSequence[random
.nextInt(codeSequence.length - 1)]);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
gd.setColor(new Color(red, green, blue));
gd.drawString(code, (i + 1) * xx, codeY);
randomCode.append(code);
}
// 将验证码保存到session中
HttpSession session = request.getSession();
session.setAttribute("vcode", randomCode.toString());
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
// 将图像输出到Servlet输出流中。
ServletOutputStream sos = response.getOutputStream();
ImageIO.write(buffImg, "jpeg", sos);
sos.close();
}
}
}

评论列表( 0 )

你可以在登录后,发表评论

10_float_left_people 10_float_left_close