servlet生成随机图片验证码

喜欢ヅ旅行 2022-06-11 02:53 412阅读 0赞

1、代码

  1. package image;
  2. import java.awt.Color;
  3. import java.awt.Font;
  4. import java.awt.Graphics;
  5. import java.awt.image.BufferedImage;
  6. import java.io.IOException;
  7. import java.util.Random;
  8. import javax.imageio.ImageIO;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import javax.servlet.http.HttpSession;
  14. public class ImageCheck extends HttpServlet{
  15. final private int WIDTH=60;//图片的宽
  16. final private int HEIGHT=30;//图片的高
  17. final private int CHECKNUMLENGTH=4;//验证码长度
  18. final private int LINENUM=15;//随即线条数量
  19. @Override
  20. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  21. //获得图片流
  22. BufferedImage bi=new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
  23. //给图片加画笔
  24. Graphics g=bi.getGraphics();
  25. //画边框
  26. g.setColor(Color.white);//背景颜色
  27. g.fillRect(1, 1, WIDTH-2, HEIGHT-2);//边框
  28. //g.drawRect(0, 0, WIDTH, HEIGHT);
  29. //改变字体大小
  30. g.setFont(new Font(null, Font.BOLD, 20));
  31. //获得随机数
  32. String str=random();
  33. //给图片加上文字
  34. g.setColor(Color.blue);
  35. g.drawString(str, 10,22);
  36. //给图片加上随即线条
  37. drawRandomLine(g);
  38. //把文字存储在session中
  39. HttpSession session = req.getSession();
  40. session.setAttribute("random", str);
  41. ImageIO.write(bi, "jpg", resp.getOutputStream());
  42. }
  43. /** * 生成随机字符串(数字加字母) */
  44. private String random() {
  45. //随机字符生成四位
  46. Random r=new Random();
  47. char[] random="1234567890abcdefghijklmopqrstuvwxyz".toCharArray();
  48. StringBuffer checkstr=new StringBuffer();
  49. for(int i=0;i<CHECKNUMLENGTH;i++){
  50. int index=r.nextInt(random.length);
  51. checkstr.append(random[index]);
  52. }
  53. return checkstr.toString();
  54. }
  55. /** * 在图片上画随机线条 * @param g */
  56. private void drawRandomLine(Graphics g) {
  57. // 设置颜色
  58. g.setColor(Color.red);
  59. // 设置线条个数并画线
  60. for (int i = 0; i < LINENUM; i++) {
  61. int x1 = new Random().nextInt(WIDTH);
  62. int y1 = new Random().nextInt(HEIGHT);
  63. int x2 = new Random().nextInt(WIDTH);
  64. int y2 = new Random().nextInt(HEIGHT);
  65. g.drawLine(x1, y1, x2, y2);
  66. }
  67. }
  68. }

2、演示图片
点击图片进行刷新

发表评论

表情:
评论列表 (有 0 条评论,412人围观)

还没有评论,来说两句吧...

相关阅读