Web端二维码生成

Web端二维码生成


在web端生成二维码的方式很多,本文记录一个传统的方式,利用java中gui绘制好二维码图像,然后传递到web端控件中。

后台代码如下:

@RequestMapping
    public void generate(HttpServletResponse response){
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        String code = drawImg(output);
        
        //将二维码值放到session中,以作匹配使用
        Subject currentUser = SecurityUtils.getSubject();  
        Session session = currentUser.getSession();
        session.setAttribute(Const.SESSION_SECURITY_CODE, code);
        
        try {
            ServletOutputStream out = response.getOutputStream();
            output.writeTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //绘制图片
    private String drawImg(ByteArrayOutputStream output){
        String code = "";
        for(int i=0; i<4; i++){
            code += randomChar();
        }
        int width = 70;
        int height = 25;
        BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
        //设置字体
        Font font = new Font("Times New Roman",Font.PLAIN,20);
        Graphics2D g = bi.createGraphics();
        g.setFont(font);
        //设置字体颜色
        Color color = new Color(66,2,82);
        g.setColor(color);
        //设置背景颜色
        g.setBackground(new Color(226,226,240));
        g.clearRect(0, 0, width, height);
        FontRenderContext context = g.getFontRenderContext();
        Rectangle2D bounds = font.getStringBounds(code, context);
        double x = (width - bounds.getWidth()) / 2;
        double y = (height - bounds.getHeight()) / 2;
        double ascent = bounds.getY();
        double baseY = y - ascent;
        //绘制
        g.drawString(code, (int)x, (int)baseY);
        g.dispose();
        try {
            ImageIO.write(bi, "jpg", output);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return code;
    }
    
    //生成随机字符
    private char randomChar(){
        Random r = new Random();
        String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
        return s.charAt(r.nextInt(s.length()));
    }

前台代码

<input type="text" style="float: left; width:50%;"  name="code" id="code" class="form-control" placeholder="请输入验证码:"/>
<img style="height:24px; margin-left:10px; float: left;" id="codeImg" alt="点击更换" title="点击更换" src="" />

脚本代码

$(document).ready(function() {
        changeCode();
        $("#codeImg").bind("click", changeCode);
    });

function genTimestamp() {
        var time = new Date();
        return time.getTime();
    }
        
function changeCode() {
        $("#codeImg").attr("src", "code.do?t=" + genTimestamp());
    }
相关文章
相关标签/搜索