gpt4 book ai didi

php - 创建给定文本的透明png

转载 作者:搜寻专家 更新时间:2023-10-31 22:05:50 25 4
gpt4 key购买 nike

我想创建一些给定文本的透明 png。我不想指定图像的宽度和高度,而是让它自动调整为文本的大小。我已经尝试过 imagemagick 和 PHP,但是,还没有完全理解。我将如何使用这些技术或任何其他技术来做到这一点?另外,为什么一种技术比另一种更好?

imagemagick 解决方案

有效,除了需要指定图像大小而不是自动调整为文本大小。

convert -size 560x85 xc:transparent -font Palatino-Bold -pointsize 72 -fill black -stroke red -draw "text 20,55 'Linux and Life'" linuxandlife.png

PHP 解决方案

除了右侧有点砍掉外,一切正常。此外,如果我使用相同字体大小和字体类型的文本制作多个图像,并且它们中都有大写字母,图像的高度并不完全相同,但我希望它们是相同的。另外,今天第一次玩图像功能,如果我做的其他事情不正确,请告诉我。

<?php

$font_size = 11;
$angle=0;
//$fonttype="/usr/share/fonts/liberation/LiberationMono-Regular.ttf";
$fonttype="/usr/share/fonts/dejavu/DejaVuSans.ttf";

$text='Some text';
$file='MyFile.png';

$bbox = imagettfbbox($font_size, $angle, $fonttype, $text);
$x1 = $bbox[2] - $bbox[0];
$y1 = $bbox[1] - $bbox[7];

$im = @imagecreatetruecolor($x1, $y1);
imagesavealpha($im, true);
imagealphablending($im, false);
$color_background = imagecolorallocatealpha($im, 255, 255, 255, 127);
imagefill($im, 0, 0, $color_background);
$color_text = imagecolorallocate($im, 255, 0, 0);
imagettftext($im, $font_size, $angle, 0, $font_size, $color_text, $fonttype, $text);
imagepng($im,$file);
imagedestroy($im);
?>

最佳答案

我会选择纯 PHP 解决方案,这样您就不会依赖像 imagemagick 这样的外部库。

也许使用浏览器缓存是个好主意,这样您就不必在每次请求时都生成图像。

Yust 在你的 'imagettfbbox' 之前添加以下代码,并将你的图像生成代码放在 ELSE 中。

$string = $text . filemtime($file);
$eTag = md5($string);
header("ETag: ".$eTag);
$httpModEtag = !empty($_SERVER['HTTP_IF_NONE_MATCH'])? $_SERVER['HTTP_IF_NONE_MATCH']:"";
if($httpModEtag===$eTag)
{
// tells the browser to use his cached image
header("HTTP/1.1 304 Not Modified", true, 304);
}
else
{
// tells the browser to refresh the cache
header("Cache-Controll: must-revalidate");

// ------ Place your Image Generation code here -------
}

关于php - 创建给定文本的透明png,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18723961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com