在php中从头创建带有文本的透明png

Ale*_*nch 7 php png image image.createimage

我在网上找到的所有例子似乎都是用现有的png文本创建png.是否可以从头开始创建透明的png,然后添加文本?

到目前为止我已经得到的代码(但它不起作用.只输出一个空白图像源)

<?php
    $width = 150;
    $height = 30;
    $text = "My Text";
    $fontsize = 5;

    $im = imagecreate($width, $height);
    $transcolor = imagecolortransparent($im);

    imagestring($im, $fontsize, 0, 0, $text, $transcolor);

    header('Content-type: image/png');
    imagepng($im);
    imagedestroy($im);
?>
Run Code Online (Sandbox Code Playgroud)

Dej*_*vic 16

<?php
    $font = 25;
    $string = 'My Text';
    $im = @imagecreatetruecolor(strlen($string) * $font / 1.5, $font);
    imagesavealpha($im, true);
    imagealphablending($im, false);
    $white = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $white);
    $lime = imagecolorallocate($im, 204, 255, 51);
    imagettftext($im, $font, 0, 0, $font - 3, $lime, "droid_mono.ttf", $string);
    header("Content-type: image/png");
    imagepng($im);
    imagedestroy($im);
?>
Run Code Online (Sandbox Code Playgroud)

如果您不想要自定义字体,请使用imagestring而不是imagettftext.


lua*_*ned 5

这是基于您的原始代码的解决方案。

<?php
    $width = 640;
    $height = 480;
    $text = "My Text";
    $fontsize = 5;

    $img = imagecreate($width, $height);

    // Transparent background
    $black = imagecolorallocate($img, 0, 0, 0);
    imagecolortransparent($img, $black);

    // Red text
    $red = imagecolorallocate($img, 255, 0, 0);
    imagestring($img, $fontsize, 0, 0, $text, $red);

    header('Content-type: image/png');
    imagepng($img);
    imagedestroy($img);
?>
Run Code Online (Sandbox Code Playgroud)