你好,可爱的群体智能!
我有一些 PHP 代码,它以网格系统的形式在图像上绘制线条,然后,它还在该图像上写入一些文本。当我使用相应的 PHP
imagecreatefrom*
和 image*
函数时,我的代码可以按预期处理 PNG 或 JPG/JPEG 等静态图像。
遵循调整和简化的(没有大量 try-catch、if 条件和变量)GIF 图像代码:
$gif_filepath = '/tmp/animated.gif';
$font_filepath = '/tmp/some-font.ttf';
list($width, $height) = getimagesize($gif_filepath);
$gd_image = imagecreatefromgif($gif_filepath);
$line_color = imagecolorallocatealpha($gd_image, 0, 0, 0, 80);
$spacing = 25;
// Draw vertical lines
for ($iw = 0; $iw < $width / $spacing; $iw++) {
imageline($gd_image, $iw * $spacing, 0, $iw * $spacing, $width, $line_color);
}
// Draw horizontal lines
for ($ih = 0; $ih < $height / $spacing; $ih++) {
imageline($gd_image, 0, $ih * $spacing, $width, $ih * $spacing, $line_color);
}
$font_color = imagecolorallocate($gd_image, 255, 0, 0);
// Write text
imagefttext($gd_image,
25,
0,
30,
60,
$font_color,
$font_filepath,
'Let\'s ask Stackoverflow!'
);
imagegif($gd_image);
PHP 正确地将相应的行和文本添加到 GIF,但最后它只返回整个 GIF 的单个(可能是第一个)帧。
是否可以使用 PHP(在最好的情况下没有任何第三方库/工具)绘制这些线条并在动画 GIF 图像上写入文本,以便之后仍然是动画的,或者这在技术上不支持/可能?
imagecopymerge
,但我无法使用此函数存档我的目标。
从技术上来说似乎不可能用 PHP 原生函数来解决这个问题。
shell_exec()
和 ffmpeg
它可以在 PHP 中存档:
$gif_filepath = '/tmp/animated.gif';
$target_image_filepath = '/tmp/modified_animated.gif';
$font_filepath = '/tmp/some-font.ttf';
$spacing = 25;
# Draw grid system (horizontal + vertical lines)
shell_exec("ffmpeg -hide_banner -loglevel error -nostdin -y -i $gif_filepath -vf 'drawgrid=width=$spacing:height=$spacing:thickness=1:[email protected]' $target_image_filepath 2>&1");
# Write text
shell_exec("ffmpeg -hide_banner -loglevel error -nostdin -y -i $gif_filepath -vf \"drawtext=text='Let\'s ask Stackoverflow!':fontsize=25:x=30:y=60:fontcolor=red:fontfile=$font_filepath\" $target_image_filepath 2>&1");
// $target_image_filepath now contains the grid system and respective text
还有一个第三方 PHP 库 PHP-FFMpeg,如果它支持 GIF 文件的相应过滤器,也许可以用来代替
shell_exec()
。