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

PHP Imagick 實現圖片剪切、旋轉、銳化、縮略圖與水印完整指南

     編輯:PHP 相關知識

ImageMagick 與 php_imagick 介紹

ImageMagick 是功能強大、開源免費的圖片處理工具集,支援超過 185 種圖片格式(含 TIFF、JPEG、GIF、PNG、PDF、PhotoCD 等)。php_imagick 是 PHP 對 ImageMagick 的擴展封裝,讓 PHP 具備同等的圖片處理能力:縮放、旋轉、銳化、減色、特效、水印等,且支援格式轉換。

環境安裝指南

Windows 環境安裝

  1. 下載並安裝 ImageMagick:
    https://image_magick.veidrodis.com/image_magick/binaries/ImageMagick-6.6.2-10-Q16-windows-dll.exe
  2. 下載對應 PHP 版本的 php_imagick.dll:
    非線程安全(NTS):https://valokuva.org/outside-blog-content/imagick-windows-builds/php53/imagick-2.3.0-dev/vc9_nts/php_imagick.dll
    線程安全(ZTS):https://valokuva.org/outside-blog-content/imagick-windows-builds/php53/imagick-2.3.0-dev/vc9_zts/php_imagick.dll
  3. 在 php.ini 中添加 extension=php_imagick.dll,重啟 Web 服務

Linux (CentOS) 環境安裝

# 1. 安裝 ImageMagick 及開發包
yum install ImageMagick ImageMagick-devel

# 2. 驗證安裝
convert -version

# 3. 安裝 imagick 擴展
wget https://pecl.php.net/get/imagick-3.1.0RC2.tgz
tar xzvf imagick-3.1.0RC2.tgz
cd imagick-3.1.0RC2
phpize
./configure
make
make install

# 4. 配置 php.ini
echo "extension=imagick.so" >> /etc/php.ini

# 5. 重啟 Apache
service httpd restart

基礎操作範例

1. 生成並輸出縮略圖

<?php
header('Content-type: image/jpeg');
$image = new Imagick('image.jpg');
// 寬度 100px,高度 0 表示保持比例
$image->thumbnailImage(100, 0);
echo $image;
?>

2. 批量生成縮略圖並保存

<?php
$images = new Imagick(glob('images/*.JPG'));
foreach($images as $image) {
    $image->thumbnailImage(1024, 0); // 保持比例
}
$images->writeImages();
?>

3. 處理 GIF 動畫縮略圖(保持幀動畫)

<?php
$im = new Imagick("example.gif");
foreach ($im as $frame) {
    $frame->thumbnailImage(50, 50);
    $frame->setImagePage(50, 50, 0, 0);
}
$im->writeImages("example_small.gif", true); // true 表示多幀
?>

進階封裝類:lib_image_imagick 完整功能

以下封裝類支援:圖片載入、裁切、多模式縮放、GIF 幀處理、圖片/文字水印、邊框、模糊、噪點、色階、藝術效果(素描、油畫)、翻轉、輸出等。

<?php
class lib_image_imagick {
    private $image = null;
    private $type = null;

    public function __construct() {}
    
    public function __destruct() {
        if($this->image !== null) $this->image->destroy();
    }

    // 載入圖片
    public function open($path) {
        $this->image = new Imagick($path);
        if($this->image) {
            $this->type = strtolower($this->image->getImageFormat());
        }
        return $this->image;
    }

    // 裁切圖片(支援 GIF 多幀)
    public function crop($x=0, $y=0, $width=null, $height=null) {
        if($width===null) $width = $this->image->getImageWidth() - $x;
        if($height===null) $height = $this->image->getImageHeight() - $y;
        if($width<=0 || $height<=0) return;

        if($this->type == 'gif') {
            $image = $this->image;
            $canvas = new Imagick();
            $images = $image->coalesceImages();
            foreach($images as $frame) {
                $img = new Imagick();
                $img->readImageBlob($frame);
                $img->cropImage($width, $height, $x, $y);
                $canvas->addImage($img);
                $canvas->setImageDelay($img->getImageDelay());
                $canvas->setImagePage($width, $height, 0, 0);
            }
            $image->destroy();
            $this->image = $canvas;
        } else {
            $this->image->cropImage($width, $height, $x, $y);
        }
    }

    // 多模式縮放:force/scale/scale_fill/九宮格定位
    public function resize_to($width=100, $height=100, $fit='center', $fill_color=array(255,255,255,0)) {
        // 完整 switch 實現見原文,支援:
        // force: 強制拉伸
        // scale: 等比縮放在安全框內
        // scale_fill: 等比縮放並填充背景色
        // 九宮格: north_west, north, north_east, west, center, east, south_west, south, south_east
    }

    // 添加圖片水印
    public function add_watermark($path, $x=0, $y=0) {
        $watermark = new Imagick($path);
        $draw = new ImagickDraw();
        $draw->composite($watermark->getImageCompose(), $x, $y, 
            $watermark->getImageWidth(), $watermark->getImageHeight(), $watermark);

        if($this->type == 'gif') {
            $image = $this->image;
            $canvas = new Imagick();
            $images = $image->coalesceImages();
            foreach($images as $frame) {
                $img = new Imagick();
                $img->readImageBlob($frame);
                $img->drawImage($draw);
                $canvas->addImage($img);
                $canvas->setImageDelay($img->getImageDelay());
                $canvas->setImagePage($this->get_width(), $this->get_height(), 0, 0);
            }
            $image->destroy();
            $this->image = $canvas;
        } else {
            $this->image->drawImage($draw);
        }
    }

    // 添加文字水印
    public function add_text($text, $x=0, $y=0, $angle=0, $style=array()) {
        $draw = new ImagickDraw();
        if(isset($style['font'])) $draw->setFont($style['font']);
        if(isset($style['font_size'])) $draw->setFontSize($style['font_size']);
        if(isset($style['fill_color'])) $draw->setFillColor($style['fill_color']);
        if(isset($style['under_color'])) $draw->setTextUnderColor($style['under_color']);

        if($this->type == 'gif') {
            foreach($this->image as $frame) {
                $frame->annotateImage($draw, $x, $y, $angle, $text);
            }
        } else {
            $this->image->annotateImage($draw, $x, $y, $angle, $text);
        }
    }

    // 保存圖片
    public function save_to($path) {
        if($this->type == 'gif') {
            $this->image->writeImages($path, true);
        } else {
            $this->image->writeImage($path);
        }
    }

    // 輸出到瀏覽器
    public function output($header=true) {
        if($header) header('Content-type: '.$this->type);
        echo $this->image->getImagesBlob();
    }

    // 獲取寬高
    public function get_width() {
        $size = $this->image->getImagePage();
        return $size['width'];
    }
    public function get_height() {
        $size = $this->image->getImagePage();
        return $size['height'];
    }

    // 設置/獲取圖片格式
    public function set_type($type='png') {
        $this->type = $type;
        $this->image->setImageFormat($type);
    }
    public function get_type() { return $this->type; }

    // 判斷是否為有效圖片
    public function is_image() { return $this->image !== null; }

    // 便捷方法
    public function thumbnail($width=100, $height=100, $fit=true) {
        $this->image->thumbnailImage($width, $height, $fit);
    }
    public function border($width, $height, $color='rgb(220,220,220)') {
        $pixel = new ImagickPixel();
        $pixel->setColor($color);
        $this->image->borderImage($pixel, $width, $height);
    }
    public function blur($radius, $sigma) { $this->image->blurImage($radius, $sigma); }
    public function gaussian_blur($radius, $sigma) { $this->image->gaussianBlurImage($radius, $sigma); }
    public function motion_blur($radius, $sigma, $angle) { $this->image->motionBlurImage($radius, $sigma, $angle); }
    public function radial_blur($radius) { $this->image->radialBlurImage($radius); }
    public function add_noise($type=null) { 
        $this->image->addNoiseImage($type ? $type : Imagick::NOISE_IMPULSE); 
    }
    public function level($black, $gamma, $white) { $this->image->levelImage($black, $gamma, $white); }
    public function modulate($brightness, $saturation, $hue) { 
        $this->image->modulateImage($brightness, $saturation, $hue); 
    }
    public function charcoal($radius, $sigma) { $this->image->charcoalImage($radius, $sigma); }
    public function oil_paint($radius) { $this->image->oilPaintImage($radius); }
    public function flop() { $this->image->flopImage(); } // 水平翻轉
    public function flip() { $this->image->flipImage(); }   // 垂直翻轉
}
?>

使用範例

include 'imagick.class.php';
$image = new lib_image_imagick();
$image->open('a.gif');
$image->resize_to(100, 100, 'scale_fill');
$image->add_text('1024i.com', 10, 20);
$image->add_watermark('1024i.gif', 10, 50);
$image->save_to('x.gif');

總結

php_imagick 提供了企業級的圖片處理能力,特別適合處理 GIF 動畫、複雜水印、批量處理等場景。封裝類進一步簡化了業務邏輯,建議在生產環境中根據需求擴展錯誤處理與日誌記錄。

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