1.简介

最近有个需求,就是把图片验证码转化为base64格式,tp5框架自带的think-captcha扩展包可以实现。但是,它有个缺点,不能获取验证码的值。在做前后端分离项目的时候,验证码检测有两种方式,各有利弊。

方式一:因为session不能共享,所以通过传递唯一uuid,后端用redis存储uuid对应的验证码,验证同理。

方式二:直接返回验证码的同时,把验证值也返回给前端,在前端去验证验证码的有效性

下面不多说,看代码。(如果你还有第三种方法,欢迎留言,共同学习)

2.代码片段

        $width = 100;
        $height = 30;
        $size = 4;
        $fontSize = 10;

        $image = imagecreatetruecolor((int)$width, (int)$height);

        $bgcolor = imagecolorallocate($image, 255, 255, 255);

        imagefill($image, 0, 0, $bgcolor);

        $content = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        
        $captcha = "";

        for ($i = 0; $i < $size; $i++) {
            $fontsize = $fontSize;

            $fontcolor = imagecolorallocate($image, mt_rand(0, 120), mt_rand(0, 120), mt_rand(0, 120));

            $fontcontent = substr($content, mt_rand(0, strlen($content)), 1);

            $captcha .= $fontcontent;

            $x = ($i * $width / 4) + mt_rand(5, 10);

            $y = mt_rand(5, 10);

            imagestring($image, $fontsize, $x, $y, $fontcontent, $fontcolor);
        }
        
        imagepng($image);
        $content = ob_get_clean();
        imagedestroy($image);
        
        $base64 = 'data:image/png;base64,' . base64_encode($content);

        return json_encode(['code' => 0, 'data' => ['base64' => $base64, 'text' => $captcha], 'message' => '操作成功']);

 

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/pitmanhuang/p/16199473.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!