image.jsp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. <%@ page pageEncoding = "gb2312" contentType="image/jpeg" import = "javax.imageio.*,java.util.*,java.awt.image.*,java.awt.*" %>
  2. <%!
  3. //在此处 获取并生成随机颜色
  4. Color getRandColor(Random random, int ff, int cc) {
  5. if (ff > 255)
  6. ff = 255;
  7. if (cc > 255)
  8. cc = 255;
  9. int r = ff + random.nextInt(cc - ff);
  10. int g = ff + random.nextInt(cc - ff);
  11. int b = ff + random.nextInt(cc - ff);
  12. return new Color(r, g, b);
  13. } %>
  14. <%
  15. //在此处 设置JSP页面无缓存
  16. response.setHeader( "Pragma" , "No-cache" );
  17. response.setHeader( "Cache-Control" , "no-cache" );
  18. response.setDateHeader( "Expires" , 0);
  19. // 设置图片的长宽
  20. int width = 130;
  21. int height = 30;
  22. //设定被随机选取的中文字,此处中文字内容过多,不一一列出,只是举例说明下。
  23. String base = "\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u538b\u6162\u53d4\u80cc\u7ec6" ;
  24. //设置 备选随机汉字的个数
  25. int length = base.length();
  26. // 创建缓存图像
  27. BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  28. // 获取图像
  29. Graphics g = image.getGraphics();
  30. // 创建随机函数的实例
  31. Random random = new Random();
  32. //此处 设定图像背景色
  33. g.setColor(getRandColor(random, 188, 235));
  34. g.fillRect(0, 0, width, height);
  35. //设置随机 备选的字体类型
  36. String[] fontTypes = { "\u5b8b\u4f53" , "\u65b0\u5b8b\u4f53" ,
  37. "\u9ed1\u4f53" , "\u6977\u4f53" , "\u96b6\u4e66" };
  38. int fontTypesLength = fontTypes.length;
  39. // 在图片背景上增加噪点,增加图片分析难度
  40. g.setColor(getRandColor(random, 180, 199));
  41. g.setFont( new Font( "Times New Roman" , Font.PLAIN, 14));
  42. for ( int i = 0; i < 4; i++) {
  43. g.drawString( "@*@*@*@*@*@*@*" ,
  44. 0, 5 * (i + 2));
  45. }
  46. // 取随机产生的验证码 (4 个汉字 )
  47. // 保存生成的汉字字符串
  48. String sRand = "" ;
  49. for ( int i = 0; i < 4; i++) {
  50. int start = random.nextInt(length);
  51. String rand = base.substring(start, start + 1);
  52. sRand += rand;
  53. // 设置图片上字体的颜色
  54. g.setColor(getRandColor(random, 10, 150));
  55. // 设置字体格式
  56. g.setFont( new Font(fontTypes[random.nextInt(fontTypesLength)],
  57. Font.BOLD, 18 + random.nextInt(6)));
  58. // 将此汉字画到验证图片上面
  59. g.drawString(rand, 24 * i + 10 + random.nextInt(8), 24);
  60. }
  61. // 将验证码存入Session中
  62. session.setAttribute( "rand" , sRand);
  63. g.dispose();
  64. //将 图象输出到JSP页面中
  65. ImageIO.write(image, "JPEG" , response.getOutputStream());
  66. //关闭流
  67. out.clear();
  68. out=pageContext.pushBody();
  69. %>