PHP生成登录图片验证码

很久之前写的 感觉登录还挺常用 记录一下。

public function makeLoginCodeAction()  //生成登录页的验证码
{
    Header("Content-type: image/PNG");
    //长与宽
    $imgW = 44;
    $imgH = 18;
    $img = imagecreate($imgW, $imgH);
    // 设置背景色:
    $back = imagecolorallocate($img, 245, 245, 245);
    // 填充背景色:
    imagefill($img, 0, 0, $back);

    srand((double)microtime() * 1000000);
    $vcodes = '';
    //生成4位数字
    for ($i = 0; $i < 4; $i++) {
        $font = imagecolorallocate($img, rand(100, 255), rand(0, 100), rand(100, 255));
        $authnum = rand(1, 9);
        $vcodes .= $authnum;
        imagestring($img, 5, 2 + $i * 10, 1, $authnum, $font);
    }

    // 将四位的验证码保存在 SESSION 里,登录时调用对比
    $_SESSION['CODE'] = $vcodes;


    //加入干扰象素
    for ($i = 0; $i < 100; $i++) {
        $randcolor = imagecolorallocate($img, rand(0, 255), rand(0, 255), rand(0, 255));
        imagesetpixel($img, rand() % 70, rand() % 30, $randcolor);
    }

    imagepng($img);
    imagedestroy($img);

    return false;
}
原文地址:https://www.cnblogs.com/xinxinmifan/p/imgVerificationCode.html