利用 PHP Imagick 擴展 (php_imagick_st-Q8.dll) 可將多張 JPG 圖片合成 GIF 動畫,支援幀延遲控制、迴圈設定、最佳化壓縮。本文詳述 Windows 環境下 DLL 安裝配置、核心合成代碼、關鍵參數調優、常見坑點與解決方案。
php -v 確認 (如 7.4.33 NTS x64)php_imagick-<版本>---.zip php_imagick.dll (無需 Q8/Q16 後綴,新版統一)magick -version 顯示版本即成功extension=imagick ; 可選:設定資源限制防止記憶體耗盡 ; imagick.memory_limit=256M ; imagick.map_limit=512M
# Apache httpd -k restart # Nginx + PHP-FPM systemctl restart php-fpm # Linux # Windows 重啟 PHP-FPM 服務或 IIS
php -m | findstr imagick 或 phpinfo() 搜尋 imagick 區塊確認載入成功。
setFormat($type); // 設定輸出格式
$animation->setIteratorIndex(0);
// 3. 逐幀加入並設定延遲
foreach ($filelist as $file) {
if (!is_file($file)) {
throw new RuntimeException("圖片不存在: $file");
}
$frame = new Imagick();
$frame->readImage($file);
// 可選:統一尺寸 (避免尺寸不一導致閃爍)
// $frame->resizeImage(800, 600, Imagick::FILTER_LANCZOS, 1);
$animation->addImage($frame);
$animation->setImageDelay($delay); // 當前幀延遲
// 釋放單幀記憶體
$frame->clear();
$frame->destroy();
}
// 4. 設定迴圈次數 (0 = 無限循環)
$animation->setOption('loop', 0);
// 5. 最佳化 (減小檔案體積)
$animation = $animation->optimizeImageLayers();
// 6. 生成輸出檔名
$filename = $prefix . time() . '.' . $type;
$fullPath = $savePath . $filename;
// 7. 寫入檔案
$animation->writeImages($fullPath, true); // true = 合併多幀為單檔
// 8. 清理記憶體
$animation->clear();
$animation->destroy();
// 9. 回傳結果
return [
'filename' => $filename,
'path' => $fullPath,
'url' => $savePath . $filename, // 相對 Web 根目錄
];
}
// ===== 使用範例 =====
$filelist = ['1.jpg', '2.jpg', '3.jpg', '4.jpg'];
$result = createGifAnimation($filelist, 'gif', 200, 'new_', './gif/', true);
if ($result) {
echo "已生成 GIF: {$result['filename']}
";
echo "
";
}
| 方法/屬性 | 作用 | 建議值 |
|---|---|---|
| setImageDelay($delay) | 單幀顯示時間 (1/100 秒) | 100-500 (1-5 秒) |
| setOption('loop', N) | 迴圈次數 | 0=無限, 1=播放一次 |
| optimizeImageLayers() | 幀差分最佳化,大幅減小體積 | 必須呼叫 |
| writeImages($path, true) | true=多幀合併單檔,false=分別輸出 | true |
| resizeImage() | 統一尺寸,避免播放跳動 | 依設計稿 |
writeImages($path, true) 第二參數為 truesetImageDelay()memory_limit 或 imagick.memory_limitclear()/destroy() 釋放// Imagick 同樣支援 WebP 動畫
$animation->setFormat('webp');
$animation->setOption('loop', 0);
$animation->writeImages('animation.webp', true);
// 體積較 GIF 小 30-50%,畫質更好,支援透明背景
掌握 Imagick 幀級控制與記憶體管理,即可構建高效穩定的圖片動畫生成服務。