支援三大核心功能(透過 type 參數切換):
__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(),但會犧牲色彩深度。