繁体   English   中英

PHP使带有文本的透明png

[英]PHP make transparent png with text

我正在运行此代码,它将创建640x1136的透明png,并在左上角投放带有黑色文字的白框。

运行时会创建代码png,但这会作为输出返回

?PNG

IHDR?z??
        IDATx???1 ?Om
??>g???IEND?B`?

有人碰巧知道这是什么吗?

同时,有人能想到一种更短的方法吗?

$im = imagecreatetruecolor(640, 1136);
imagesavealpha($im, true);
$color = imagecolorallocatealpha($im, 0, 0, 0, 127);
imagefill($im, 0, 0, $color);
imagepng($im);
imagesavealpha($im, true); // important to keep the png's transparency 
$text_color = imagecolorallocate($im, 0, 0, 0);
$width = 640; // the width of the image
$height = 1136; // the heighst of the image
$font_size = 20; // font size
$box_color = imagecolorallocate($im, 255, 255, 255);
// Set the offset x and y for the text position
$offset_x = 0;
$offset_y = 20;
$dims = imagettfbbox($font_size, 0, $font, $text);
$text_width = $dims[4] - $dims[6] + $offset_x;
$text_height = $dims[3] - $dims[5] + $offset_y;
// Add text background
imagefilledrectangle($im, 0, 0, $text_width, $text_height, $box_color);
// Add text
imagettftext($im, $font_size, 0, $offset_x, $offset_y, $text_color, $font,$text);
imagepng($im, $img, 0);

您应该使用数据发送正确的header

header('Content-Type: image/png');

或者,如果您是从控制台尝试的,并且希望将输出定向到PNG文件,则应以php <yourscript>.php > filename.png形式运行它,或更改imagepng($im); imagepng($im, 'filename.png'); 您的脚本当前正在执行的操作是将PNG输出到输出中,您会看到原始的PNG数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM