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

PHP 圖片處理類:縮放、裁剪與水印功能完整實作

     編輯:PHP 綜合知識

功能概覽

支援三大核心功能(透過 type 參數切換):

  1. 縮放:等比例縮放,支援透明度保留
  2. 裁剪:指定座標與尺寸裁剪
  3. 圖片水印:9 種預設位置 + 隨機位置

建構子參數

__construct($imageaddress, $types, $value1="", $value2="", $endaddress)
/*
$types 功能編號:
  1 = 縮放,$value1=目標寬度,$value2=目標高度
  2 = 裁剪,$value1=起始座標"x,y",$value2=裁剪尺寸"w,h"
  3 = 水印,$value1=水印圖片路徑,$value2=位置代碼(1-9,0)
$endaddress 輸出檔案完整路徑
*/

核心方法解析

圖片資源載入

private function imagesources($imgad)
{
    $imagearray = getimagesize($imgad);
    switch($imagearray[2]) {
        case 1: $this->imgtype=1; return imagecreatefromgif($imgad);
        case 2: $this->imgtype=2; return imagecreatefromjpeg($imgad);
        case 3: $this->imgtype=3; return imagecreatefrompng($imgad);
        default: return false;
    }
}

等比縮放算法

private function proimagesize()
{
    if($this->value1 && ($this->width < $this->height)) {
        $this->value1 = round(($this->value2 / $this->height) * $this->width);
    } else {
        $this->value2 = round(($this->value1 / $this->width) * $this->height);
    }
}

透明度處理

$tran = imagecolortransparent($this->image);
if($tran >= 0 && $tran < imagecolorstotal($this->image)) {
    $tranarr = imagecolorsforindex($this->image, $tran);
    $newcolor = imagecolorallocate($newimg, $tranarr['red'], $tranarr['green'], $tranarr['blue']);
    imagefill($newimg, 0, 0, $newcolor);
    imagecolortransparent($newimg, $newcolor);
}

水印位置計算

private function position($num, $width, $height)
{
    switch($num) {
        case 1: return [0, 0];                    // 左上
        case 2: return [($this->width-$width)/2, 0];      // 上中
        case 3: return [$this->width-$width, 0];          // 右上
        case 4: return [0, ($this->height-$height)/2];    // 左中
        case 5: return [($this->width-$width)/2, ($this->height-$height)/2]; // 置中
        case 6: return [$this->width-$width, ($this->height-$height)/2];     // 右中
        case 7: return [0, $this->height-$height];       // 左下
        case 8: return [($this->width-$width)/2, $this->height-$height];     // 下中
        case 9: return [$this->width-$width, $this->height-$height];         // 右下
        case 0: return [rand(0, $this->width-$width), rand(0, $this->height-$height)]; // 隨機
    }
}

使用範例

// 縮放至 300x200
$img = new Image('source.jpg', 1, 300, 200, 'thumb.jpg');
$img->outimage();

// 裁剪 (100,100) 起始,200x200 區域
$img = new Image('source.jpg', 2, '100,100', '200,200', 'crop.jpg');
$img->outimage();

// 加水印,置中
$img = new Image('source.jpg', 3, 'watermark.png', 5, 'watermarked.jpg');
$img->outimage();

已知限制

使用 imagecreatetruecolor() 建立畫布時,PNG 透明度處理可能不完美。若透明度為關鍵需求,可改用 imagecreate(),但會犧牲色彩深度。

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