验证码的变换

xiaoxiao2021-02-28  82

//验证码 public String imageCode() throws IOException{ //获得验证码随机数 String code = ImageUtil1.getRandomCode(4); BufferedImage img = ImageUtil1.createImage(code); ValueStackUtil.setSessionAttribute("imgCode", code); ImageIO.write(img, "png", ServletActionContext.getResponse().getOutputStream()); return null; } 点击验证码变换 <tr> <td valign="middle" align="right"> 验证码: <img id="num" src="<s:url value='/user/user_imageCode'/>" οnclick='this.src=this.src+"?c="+Math.random()'/> </td> <td valign="middle" align="left"> <input id="code" type="text" required="true" class="inputgri" name="code" /> </td> </tr> 点击换一张更换验证码 <script type="text/javascript"> function fun(){ var img1 = document.getElementById("num"); img1.src = "<s:url value='/user/user_imageCode'/>;" + new Date();          }  </script> <tr> <td valign="middle" align="right"> 验证码: <img id="num" src="<s:url value='/user/user_imageCode'/>" /> <a href="javascript:void(0)" οnclick="fun()">换一张</a> </td> <td valign="middle" align="left"> <input type="text" class="inputgri" name="code" /> </td> </tr> 验证码的util方法: public class ImageUtil { public static String getRandomCode(int n){ String str = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; int len = str.length(); StringBuffer sb = new StringBuffer(); Random r = new Random(); for(int i=0;i<n;i++){ sb.append(str.charAt(r.nextInt(len))); } return sb.toString(); } public static BufferedImage createImage(String securityCode){        int codeLength = securityCode.length();//验证码长度        int fontSize = 20;//字体大小        int fontWidth = fontSize+1;        //图片宽高        int width = codeLength*fontWidth+60;        int height = fontSize*2;        //图片        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);        Graphics2D g = image.createGraphics();        g.setColor(Color.WHITE);//设置背景色        g.fillRect(0, 0, width, height);//填充背景        g.setColor(Color.LIGHT_GRAY);//设置边框颜色        g.setFont(new Font("Courier New", Font.BOLD, height-2));//边框字体样式        g.drawRect(0, 0,0, 0);//绘制边框        //绘制噪点        Random rand = new Random();        g.setColor(Color.LIGHT_GRAY);        for (int i = 0; i < codeLength*6; i++) {            int x = rand.nextInt(width);            int y = rand.nextInt(height);            g.drawRect(x, y, 1, 1);//绘制1*1大小的矩形        }        //绘制验证码        int codeY = height-10;        g.setColor(new Color(19,148,246));        g.setFont(new Font("Georgia", Font.BOLD, fontSize));        for(int i=0;i<codeLength;i++){         double deg=new Random().nextDouble()*20;         g.rotate(Math.toRadians(deg), i*16+13,codeY-7.5);            g.drawString(String.valueOf(securityCode.charAt(i)), i*16+5, codeY);            g.rotate(Math.toRadians(-deg), i*16+13,codeY-7.5);        }               g.dispose();//关闭资源        return image;    } }
转载请注明原文地址: https://www.6miu.com/read-71020.html

最新回复(0)