【问题标题】:imagemagick for captcha用于验证码的 imagemagick
【发布时间】:2012-02-11 11:39:00
【问题描述】:

我有一个 cronjob 可以为我的在线表单(注册、联系方式和时事通讯)生成验证码。

我每天生成超过 5000 张图像,所以当我显示表单时,我随机选择一张,然后简单地显示图像并设置会话。

我的表很简单:

captcha (id mediumint(5) unsigned PK, 短语 varchar(10));

然后我运行生成图像并插入数据库的 cronjob。这个过程需要一段时间才能运行,我想知道是否有更好的方法来做到这一点,以最大限度地提高性能和生成,因为我有其他整天运行的 cronjob,我想确保我可以把它从 cronjob 中拿走这样我的 cronjob 工作就可以喘口气了。

【问题讨论】:

  • 如果您总共有超过 5000 个联系人或时事通讯,那么您很受欢迎 :) 这似乎相当低效且浪费资源。仅在需要时生成图像。
  • 好吧,我生成 5000 以确保当我随机化时,我不会得到相同的两次。
  • @Owan Bakudan 是对的,您应该使用 GD 即时生成它们。我认为您不需要 cronjob 来执行此操作
  • @BookOfZeus 我读到我需要使用 imagecreate 但它有点复杂有什么我可以玩的吗?
  • @Owan 首先你必须检查 GD 是否启用,你可以使用 php info 检查并搜索 GD。

标签: cron imagemagick captcha


【解决方案1】:

创建一个文件调用Captcha.class.php 并输入:

class Captcha {
    private $font = '/path/to/font/yourfont.ttf'; // get any font you like and dont forget to update this.

    private function generateCode($characters) {
        $possible = '23456789bcdfghjkmnpqrstvwxyz'; // why not 1 and i, because they look similar and its hard to read sometimes
        $code = '';
        $i = 0;
        while ($i < $characters) {
            $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
            $i++;
        }
        return $code;
    }

    function getImage($width, $height, $characters) {
        $code = $this->generateCode($characters);
        $fontSize = $height * 0.75;
        $image = imagecreate($width, $height);
        if(!$image) {
            return FALSE;
        }
        $background_color = imagecolorallocate($image, 255, 255, 255);
        $text_color = imagecolorallocate($image, 66, 42, 32);
        $noiseColor = imagecolorallocate($image, 150, 150, 150);
        for( $i=0; $i<($width*$height)/3; $i++ ) {
            imagefilledellipse($image, mt_rand(0,$width), mt_rand(0,$height), 1, 1, $noiseColor);
        }
        for( $i=0; $i<($width*$height)/150; $i++ ) {
            imageline($image, mt_rand(0,$width), mt_rand(0,$height), mt_rand(0,$width), mt_rand(0,$height), $noiseColor);
        }
        $textbox = imagettfbbox($fontSize, 0, $this->font, $code);
        if(!$textbox) {
            return FALSE;
        }
        $x = ($width - $textbox[4])/2;
        $y = ($height - $textbox[5])/2;
        imagettftext($image, $fontSize, 0, $x, $y, $text_color, $this->font , $code) or die('Error in imagettftext function');
        header('Content-Type: image/jpeg');
        imagejpeg($image);
        imagedestroy($image);
        $_SESSION['captcha'] = $code;
    }
}

然后在你的页面中你可以这样做:

&lt;img src="/captcha.php" /&gt;

然后在/captcha.php你会放:

session_start();
require('Captcha.class.php');
$Captcha = new Captcha();
$Captcha->getImage(120,40,6);

您也可以根据需要更改参数以显示不同的验证码。

这样您就可以即时生成。您也可以随时将图像保存在磁盘上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-11
    • 2016-03-02
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多