首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP Imagick 擴展實現 JPG 合成 GIF 動畫完整教程

     編輯:PHP 相關知識

基於 php_imagick_st-Q8.dll 的圖片合成動畫實戰

擴展安裝配置

  1. 下載 php_imagick_st-Q8.dll 放入 PHP ext/ 目錄
  2. 修改 php.ini 添加:extension=php_imagick_st-Q8.dll(去掉分號)
  3. 重啟 Apache 或 IIS

JPG 轉 GIF 動畫核心代碼

<?php
$filelist = array('1.jpg', '2.jpg', '3.jpg', '4.jpg');
$type = 'gif';
$num = 200;        // 幀延遲(毫秒)
$qian = 'new_';    // 輸出文件前綴
$path = './gif/';  // 保存路徑
$is = 1;           // 是否預覽

get_img($filelist, $type, $num, $qian, $path, $is);

function get_img($filelist, $type, $num, $qian, $path, $is) {
    $animation = new Imagick();
    $animation->setFormat($type);
    
    foreach ($filelist as $file) {
        $image = new Imagick();
        $image->readImage($file);
        $animation->addImage($image);
        $animation->setImageDelay($num);
        unset($image);  // 釋放內存
    }
    
    $images = $qian . time() . '.' . $type;
    $animation->writeImages($images, true);  // true = 多幀合併
    copy($images, $path . $images);
    unlink($images);  // 刪除臨時文件
    
    if ($is) {
        echo "已生成: $images <br/><img src='$path$images' />";
    } else {
        echo "已生成: $images <br/>";
    }
}

關鍵參數說明

  • setImageDelay($num):設置幀延遲,單位為百分之一秒(200 = 2 秒)
  • writeImages($filename, true):第二參數 true 表示將所有幀寫入單個文件
  • unset($image):及時釋放單幀內存,防止大量圖片導致內存溢出

Imagick 還支援圖片縮放、裁剪、特效等高級操作,可結合 resizeImage()、cropImage() 實現更豐富的動畫生成需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved