使用 PHP 在动画 GIF 图像上画线和写文本

Draw lines and write text on animated GIF image using PHP

提问人:checker284 提问时间:10/1/2023 最后编辑:Christoph Rackwitzchecker284 更新时间:10/7/2023 访问量:62

问:

你好,可爱的群体智能!

我有一些PHP代码,它以网格系统的形式在图像上绘制线条,然后,它还在这个图像上写了一些文本。当我使用相应的 PHP 和函数时,我的代码可以按预期处理 PNG 或 JPG/JPEG 等静态图像。imagecreatefrom*image*

按照调整和简化的 GIF 图像代码(没有大量 try-catch、if 条件和变量):

$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 图像上写入文本,以便它之后仍然动画,或者这在技术上不受支持/不可能?

我已经看到,有一个PHP函数imagecopymerge,但我无法用这个函数存档我的目标。

php 绘图 gif gd 动画 gif

评论

3赞 IMSoP 10/1/2023
也许您已经意识到了这一点,但“之后它不再是真正的 GIF”并不是真的——GIF 只是一种文件格式,可以表示静止图像和动画图像;只是其他格式在静止图像中变得越来越普遍。因此,您真正的问题就变成了如何编辑动画图像的帧
0赞 checker284 10/1/2023
好点子。我会稍微调整一下我的问题。

答:

0赞 checker284 10/7/2023 #1

从技术上讲,使用 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()