成语验证码

1.效果图

 

 

 2.准备一个成语文本文档

eg:

 

 

3.实现代码

public class MyValidCode {
public static void getCode(int width, int height, HttpServletRequest req, HttpServletResponse resp) throws Exception {
// TODO Auto-generated method stu
File file = new File("C:\\Users\\Mike-Qian\\Desktop\\cydq.txt");//成语存放文本中位置
Random random = new Random();
int font[]={15,20,25,23,28}; //字体font
String[] fontNames={"宋体","华文楷体","黑体","微软雅黑","楷体_GB2312","隶书"};//字体类型
Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN, Color.RED, Color.BLACK, Color.ORANGE,
Color.CYAN };//字体颜色
FileInputStream f = new FileInputStream(file);
BufferedReader br = new BufferedReader(new InputStreamReader(f,"utf-8"));
ArrayList<String> list = new ArrayList<String>();
String line=null;
while((line=br.readLine())!=null)
{
list.add(line);
}
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
g.setColor(new Color(255, 255, 255));
g.fillRect(0, 0, width, height);
for (int i = 0; i < 30; i++) {
g.setColor(colors[random.nextInt(colors.length)]);
final int x = random.nextInt(width);
final int y = random.nextInt(height);
final int w = random.nextInt(20);
final int h = random.nextInt(20);
final int signA = random.nextBoolean() ? 1 : -1;
final int signB = random.nextBoolean() ? 1 : -1;
g.drawLine(x, y, x + w * signA, y + h * signB);
}
//key
String str=list.get(random.nextInt(list.size()));
HttpSession session = req.getSession();
session.setAttribute("checkCode", str);
String val=str+list.get(random.nextInt(list.size())).charAt(2);
char[] charArray = val.toCharArray();
java.util.List sList = toSuffle(charArray);
for(int i=0;i<sList.size();i++)
{
g.setFont(new Font(fontNames[random.nextInt(font.length)],Font.BOLD,font[random.nextInt(font.length)]));
g.setColor(colors[random.nextInt(colors.length)]);
g.drawString(sList.get(i)+"", i * (width / 5)+5, height - (height / 3));
}
resp.setHeader("expires","-1");
resp.setHeader("PRagma","no-cache");
resp.setHeader("cache-control","no-cache");
ImageIO.write(bi,"jpg", resp.getOutputStream());
}
private static List toSuffle(char[] arr) {
ArrayList list = new ArrayList();
for(int i=0;i<arr.length;i++)
{
list.add(arr[i]);
}
Collections.shuffle(list);
return list;
}
}

 

 

posted @ 2021-10-11 15:14  ItRanger001  阅读(174)  评论(0编辑  收藏  举报