验证码的生成

布满荆棘的人生 2023-06-13 09:25 78阅读 0赞
  1. import java.awt.Color;
  2. import java.awt.Font;
  3. import java.awt.Graphics;
  4. import java.awt.image.BufferedImage;
  5. import java.io.IOException;
  6. import java.util.Random;
  7. import javax.imageio.ImageIO;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import com.lutongnet.constant.AbstractSessionData;
  13. /** * 验证码控制器 * @author lizhangyu * @Date 2019-11-14 */
  14. @Controller
  15. public class VerifyCodeController {
  16. /** * 获取随机颜色 * @param fc 种子数 * @param bc 种子数 * @return 颜色对象 */
  17. public Color getRandColor(int fc, int bc) {
  18. Random random = new Random();
  19. if (fc > 255) {
  20. fc = 255;
  21. }
  22. if (bc > 255) {
  23. bc = 255;
  24. }
  25. int r = fc + random.nextInt(bc - fc);
  26. int g = fc + random.nextInt(bc - fc);
  27. int b = fc + random.nextInt(bc - fc);
  28. return new Color(r, g, b);
  29. }
  30. /** * 生成校验码 * @param request HttpServletRequest对象 * @param response HttpServletResponse对象 * @throws IOException IO操作异常 */
  31. @RequestMapping(value = "/login/verifyCode")
  32. public void genereate(HttpServletRequest request, HttpServletResponse response) throws IOException {
  33. int width = 60;
  34. int height = 20;
  35. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  36. Graphics g = image.getGraphics();
  37. Random random = new Random();
  38. g.setColor(getRandColor(200, 250));
  39. g.fillRect(0, 0, width, height);
  40. g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
  41. g.setColor(getRandColor(160, 200));
  42. for (int i = 0; i < 10; i++) {
  43. int x = random.nextInt(width);
  44. int y = random.nextInt(height);
  45. int xl = random.nextInt(12);
  46. int yl = random.nextInt(12);
  47. g.drawLine(x, y, x + xl, y + yl);
  48. }String sRand = "";
  49. for (int i = 0; i < 4; i++) {
  50. String rand = String.valueOf(random.nextInt(10));
  51. sRand += rand;
  52. g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
  53. g.drawString(rand, 13 * i + 6, 16);
  54. }
  55. request.getSession().setAttribute(AbstractSessionData.VERIFY_CODE, sRand);
  56. g.dispose();
  57. response.setHeader("Pragma", "No-cache");
  58. response.setHeader("Cache-Control", "no-cache");
  59. response.setDateHeader("Expires", 0);
  60. ImageIO.write(image, "JPEG", response.getOutputStream());
  61. response.getOutputStream().close();
  62. }
  63. }

发表评论

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

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

相关阅读

    相关 验证生成

    视图函数里 > 1,导入图片,画布,画笔,画笔上的字体,定义坐标 > 2,从外部导入字体(字体导入到static静态中) > 3,随机生成验证码,验证码颜色,验证