【问题标题】:Text is disappearing when I try to add an image in PHP + GD library当我尝试在 PHP + GD 库中添加图像时,文本消失了
【发布时间】:2018-09-13 20:56:37
【问题描述】:

我正在尝试创建一个包含一些文本和缩放图片的 PNG。这是文本的代码,它工作正常:

<?php
session_start();
error_reporting(E_ALL);

$label = imagecreate(500, 500);
imagecolorallocate($label, 0, 0, 0);

// up text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 150, $color, "arial.ttf", "UP UP UP");

// down text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 350, $color, "assets/fonts/arial.ttf", "DOWN DOWN DOWN");

header('Content-type: image/png');
imagepng($label);
imagedestroy($label);
die();
?>

通过上面的代码,你得到了下面的图片,这是正确的:

现在我想在里面放一张小图片,所以我从 JPEG 文件 (adidas.jpg) 加载图片。这是代码

<?php
session_start();
error_reporting(E_ALL);


$label = imagecreate(500, 500);
imagecolorallocate($label, 0, 0, 0);


// up text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 150, $color, "arial.ttf", "UP UP UP");

// image
$src = imagecreatefromjpeg("adidas.jpg");
$pic = imagecreatetruecolor(500, 500);
imagecopyresampled($label, $src, 0, 0, 0, 0, 150, 150, imagesx($src), imagesy($src));
$white = imagecolorallocate($pic, 255, 255, 255);
imagefill($label,0,0,$white);
imagedestroy($pic);


// down text
$color = imagecolorallocate($label, 255, 255, 255);
imagettftext($label, 50, 0, 0, 350, $color, "arial.ttf", "DOWN DOWN DOWN");

header('Content-type: image/png');
imagepng($label);
imagedestroy($label);
die();
?>

这就是我得到的:

令我惊讶的是,“向下”文本消失了。这是为什么? 图片前加的文字没问题,后加的文字不知为何变黑了

【问题讨论】:

    标签: php html image gd imagecreatefrompng


    【解决方案1】:

    您的代码有点乱,如果您删除第二个,则会出现“DOWN..”文字:

    $color = imagecolorallocate($label, 255, 255, 255);
    

    您没有填充原始图像,您稍后尝试但颜色错误($white 来自 $pic,而不是 $label)。 我清理了它:

    <?php
    session_start();
    error_reporting(E_ALL);
    
    $label = imagecreate(500, 500);
    $black = imagecolorallocate($label, 0, 0, 0);
    $white = imagecolorallocate($label, 255, 255, 255);
    imagefill($label, 0, 0, $black);
    
    imagettftext($label, 50, 0, 0, 150, $white, "arial.ttf", "UP UP UP");
    
    $src = imagecreatefromjpeg("adidas.jpg");
    $pic = imagecreatetruecolor(500, 500);
    imagecopyresampled($label, $src, 0, 0, 0, 0, 150, 150, imagesx($src), imagesy($src));
    $white2 = imagecolorallocate($pic, 255, 255, 255);
    
    imagettftext($label, 50, 0, 0, 350, $white, "arial.ttf", "DOWN DOWN DOWN");
    
    ob_end_clean();
    header('Content-type: image/png');
    imagepng($label);
    
    imagedestroy($src);
    imagedestroy($pic);
    imagedestroy($label);
    die();
    ?>
    

    【讨论】:

    • 使用您的代码,文本(“向上”和“向下”)都消失了。请尝试
    • 如果两个文本都消失了,请检查字体路径。
    • 你是对的,字体路径错误,现在可以了,我看到两个文本
    猜你喜欢
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2019-03-23
    • 2011-07-19
    • 1970-01-01
    • 2016-05-14
    相关资源
    最近更新 更多