java生成图片验证码

来源:互联网 发布:淘宝swatch是真的吗 编辑:程序博客网 时间:2024/05/29 19:34
    public void doGet(HttpServletRequest request, HttpServletResponse response)              throws ServletException, IOException {             //设置输出类型和浏览器不保存缓存           response.setContentType("image/jpeg") ;           response.setHeader("Cache-Control", "no-cache") ;                      //创建图片对象           int width = 60,height = 20 ;           BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB) ;                      Graphics g = image.getGraphics() ;                      //初始化种子         String[] str={"0","1","2","3","4","5","6","7","8","9",              "a","b","c","d","e","f","g","h","i","j",              "k","l","m","n","p","q","r","s","t"};         int number=str.length;                  Random random = new Random() ;           String text = "";         //随机产生4个字符的字符串         for(int i=0;i<4;i++){          text+=str[random.nextInt(number)];         }                  //把随机数存到Session里面,便于等下比较           HttpSession session = request.getSession() ;           session.setAttribute("code",text) ;                      //随机生成颜色  Color color =  new Color(255,255,255) ;     random.nextInt(256)的值范围是0~255           Color color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256)) ;                      //把随机数写到图片上           String a = null ;           Font font = new Font(a,Font.ITALIC,18) ;           g.setColor(color) ;           g.setFont(font);           g.drawString(text,10,height-5) ;           g.dispose() ;    //关闭画笔                      //把图片送到客户端           ServletOutputStream output = response.getOutputStream() ;           ImageIO.write(image,"JPEG",output) ;           output.flush();   //关闭输出流      } 

原创粉丝点击