使用ImageMagick和php在动画gif上添加文本


Adding text on animated gif with ImageMagick and php

我尝试使用ImageMagick在动画gif上添加文本:

$source = public_path().'/test.gif';
$output = public_path().'/test2.gif';
$text = 'the cake is a lie';
// Create objects
$image = new Imagick($source);
// Create a new drawing palette
$draw = new ImagickDraw();
// Set font properties
$draw->setFont(public_path().'/fonts/Impact.ttf');
$draw->setFontSize(20);
$draw->setFillColor('black');
// Position text at the bottom-right of the image
$draw->setGravity(Imagick::GRAVITY_SOUTHEAST);
// Draw text on the image
$image->annotateImage($draw, 10, 12, 0, $text);
// Draw text again slightly offset with a different color
$draw->setFillColor('white');
$image->annotateImage($draw, 11, 11, 0, $text);
// Set output image format
$image->setImageFormat('gif');
$image->writeImage($output);

但是使用此代码,图像不再动画并且质量非常差,知道吗?

终于找到了:

exec('/usr/local/bin/convert '.$source_img.' -font '.$font_location.' -pointsize 14 -draw "gravity south fill black text 0,12 ''some text'' fill white text 1,11 ''some text'' " '.$output_img);
您可能

希望使用 -coalesce 方法从 GIF 帧中删除所有优化,然后对其进行标记,然后使用 -layers Optimize 重新设置动画,因为否则各种优化(针对调色板和帧间差异)会干扰并降低标签的质量。

因此,在命令行中,过程如下所示:

convert animation.gif -coalesce '
      -gravity SouthEast -background white ... <do label here>
      -layers Optimize output.gif

参考:在此处查看 ImageMagick 文档

我不倾向于使用 PHP,但似乎有一些方法与上述功能匹配:

Imagick Imagick::coalesceImages ( void )

文档

bool Imagick::optimizeImageLayers ( void )

文档