使用PHP在GIF动画图像上绘制线条和编写文本

vwkv1x7d  于 12个月前  发布在  PHP
关注(0)|答案(1)|浏览(98)

你好可爱的群体智慧!
我有一些PHP代码,它以网格系统的形式在图像上绘制线条,然后,它还在此图像上写入一些文本。当我使用各自的PHP imagecreatefrom*image*函数时,我的代码可以像预期的那样处理PNG或JPG/JPEG等静态图像。
下面是调整和简化后的GIF图像代码(没有大量的try-catch,if-conditions和变量):

$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,但是我不能用这个函数归档我的目标。

qzlgjiam

qzlgjiam1#

从技术上讲,似乎不可能用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 library PHP-FFMpeg,如果它支持GIF文件的相应过滤器,则可以使用它来代替shell_exec()

相关问题