php -m | grep gd)frames/ 目錄GIFEncoder.class.php此類別封裝 GIF89a 格式組裝邏輯,支援:
url 或 bin 模式)// 關鍵方法簽名
class GIFEncoder {
public function __construct(
array $GIF_src, // 幀來源:檔案路徑陣列或二進位字串陣列
array $GIF_dly, // 每幀延遲 (百分之一秒,100=1秒)
int $GIF_lop, // 循環次數 (0=無限)
int $GIF_dis, // 處置方式 (0=無, 1=不處置, 2=還原背景, 3=還原前一幀)
int $GIF_red, // 透明色 R (-1=無)
int $GIF_grn, // 透明色 G
int $GIF_blu, // 透明色 B
string $GIF_mod // 'url' 或 'bin'
) {}
public function GetAnimation(): string {} // 回傳二進位 GIF 資料
}
GetAnimation();
$gw) { $xv = -$xv; $x = $gw - ($x - $gw); }
elseif ($x < 0) { $xv = -$xv; $x = -$x; }
if ($y > $gh) { $yv = -$yv; $y = $gh - ($y - $gh); }
elseif ($y < 0) { $yv = -$yv; $y = -$y; }
$path[] = [$x,$y];
} while ($x !== $path[0][0] || $y !== $path[0][1]);
$framesBin = [];
foreach ($path as $frame) {
$im = imagecreate($w, $h);
$black = imagecolorallocate($im, 0,0,0);
$white = imagecolorallocate($im, 255,255,255);
$red = imagecolorallocate($im, 255,0,0);
// 左邊板
$py = min($frame[1], $h - $pad*3);
imagefilledrectangle($im, 0, $py, $pad, $py+$pad*3, $white);
// 右邊板
imagefilledrectangle($im, $w-$pad, 0, $w, $h, $red);
// 球
imagefilledrectangle($im, $pad+$frame[0], $frame[1], $pad+$frame[0]+$ball, $frame[1]+$ball, $white);
imagegif($im);
$framesBin[] = ob_get_clean(); // 取得二進位並清空緩衝
imagedestroy($im);
}
$gif = new GIFEncoder($framesBin, array_fill(0, count($framesBin), 10), 0, 2, 0, 0, 1, 'bin');
header('Content-Type: image/gif');
echo $gif->GetAnimation();
| 參數 | 建議值 | 影響 |
|---|---|---|
延遲 $GIF_dly | 10~20 (0.1~0.2秒) | 太小檔案大、太大卡頓 |
循環 $GIF_lop | 0 (無限) | 廣告建議 3~5 循環避免干擾 |
處置 $GIF_dis | 2 (還原背景) | 透明背景動畫必設 |
| 透明色 | 背景主色調 | 消除鋸齒白邊 |
ffmpeg -i frame_%04d.png -vf "fps=10,scale=320:-1:flags=lanczos" out.gifimagewebp PHP 7.0+)、APNG、CSS/JS 前端動畫syahrul/gif-encoder、kornrunner/gifencoder (更現代 OOP 介面)