首页 > 解决方案 > 如何实现 php imagecreatetruecolor 从 php 5 到 php 7

问题描述

我有一个带有 imagecreatetruecolor 的验证码创建者,当我使用 php 5 时,这是可行的,但现在在 php 7 中没有。我没有对文件进行任何更改,我找不到与文档有任何区别。

我已经在 chrome、edge 和 firefox 中尝试过,在任何导航器作品中。

这是我的代码。

#create image and set background color
$captcha = imagecreatetruecolor(120,35);
$color = rand(128,160);
$background_color = imagecolorallocate($captcha, $color, $color, $color);
imagefill($captcha, 0, 0, $background_color);

#draw some lines
for($i=0;$i<10;$i++){
    $color = rand(48,96);
    imageline($captcha, rand(0,130),rand(0,35), rand(0,130), rand(0,35),imagecolorallocate($captcha, $color, $color, $color));
}

#generate a random string of 5 characters
$string = substr(md5(rand()*time()),0,5);

#make string uppercase and replace "O" and "0" to avoid mistakes
$string = strtoupper($string);
$string = str_replace("O","B", $string);
$string = str_replace("0","C", $string);

#save string in session "captcha" key
session_start();
$_SESSION["captcha"]=$string;

#place each character in a random position
putenv('GDFONTPATH=' . realpath('.'));
$font = 'arial.ttf';
for($i=0;$i<5;$i++){
    $color = rand(0,32);
    if(file_exists($font)){
        $x=4+$i*23+rand(0,6);
        $y=rand(18,28);
        imagettftext  ($captcha, 15, rand(-25,25), $x, $y, imagecolorallocate($captcha, $color, $color, $color), $font, $string[$i]);
    }else{
        $x=5+$i*24+rand(0,6);
        $y=rand(1,18);
        imagestring($captcha, 5, $x, $y, $string[$i], imagecolorallocate($captcha, $color, $color, $color));
    }
}

#applies distorsion to image
$matrix = array(array(1, 1, 1), array(1.0, 7, 1.0), array(1, 1, 1));
imageconvolution($captcha, $matrix, 16, 32);

#avoids catching
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); 

#return the image
header("Content-type: image/jpeg");
imagejpeg($captcha);

这是输出:

输出

在专用选项卡中:

专用选项卡中的验证码

标签: php

解决方案


谢谢大家,当我删除header("Content-type: image/jpeg");显示警告时,调用验证码字体时出错。

我变了:

$font = 'arial.ttf';

为了:

$font = '/arial.ttf';

然后它工作正常。


推荐阅读