yanzhengma.jsp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <%@ page contentType="image/jpeg" language="java" import="java.util.*,java.awt.*,java.awt.image.*,javax.imageio.*" pageEncoding="utf-8"%>
  2. <%!
  3. Color getRandColor(int fc,int bc){
  4. Random random = new Random();
  5. if(fc > 255){
  6. fc = 255;
  7. }
  8. if(bc < 255){
  9. bc = 255;
  10. }
  11. int r = fc +random.nextInt(bc-fc);
  12. int g = fc +random.nextInt(bc-fc);
  13. int b = fc +random.nextInt(bc-fc);
  14. return new Color(r,g,b);
  15. }
  16. %>
  17. <%
  18. //设置页面不缓存
  19. response.setHeader("Pragma","no-cache");
  20. response.setHeader("Cache-Control","no-catch");
  21. response.setDateHeader("Expires",0);
  22. //在内存中创建图象
  23. int width = 60;
  24. int height = 20;
  25. BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
  26. //创建图象
  27. Graphics g = image.getGraphics();
  28. //生成随机对象
  29. Random random = new Random();
  30. //设置背景色
  31. g.setColor(getRandColor(200,250));
  32. g.fillRect(0,0,width,height);
  33. //设置字体
  34. g.setFont(new Font("Tines Nev Roman",Font.PLAIN,18));
  35. //随机产生干扰线
  36. g.setColor(getRandColor(160,200));
  37. for(int i = 0; i < 255; i++){
  38. int x = random.nextInt(width);
  39. int y = random.nextInt(height);
  40. int xl = random.nextInt(12);
  41. int yl = random.nextInt(12);
  42. }
  43. //随机产生认证码,4位数字
  44. String sRand = "";
  45. for(int i = 0; i < 4; i++){
  46. String rand = String.valueOf(random.nextInt(10));
  47. sRand += rand;
  48. //将认证码显示到图象中
  49. g.setColor(new Color(20 + random.nextInt(110),20 + random.nextInt(110),20 + random.nextInt(110)));
  50. g.drawString(rand,13*i+6,16);
  51. }
  52. session.setAttribute("rCode",sRand);
  53. //图像生效
  54. g.dispose();
  55. //输出图像到页面
  56. ImageIO.write(image,"JPEG",response.getOutputStream());
  57. out.clear();
  58. out = pageContext.pushBody();
  59. %>