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 数据。
我是 运行 此代码创建一个 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 数据。