<?php
// 保留 PNG 透明通道
$src = imagecreatefrompng('logo.png');
$dst = imagecreatetruecolor(200, 200);
imagealphablending($dst, false);
imagesavealpha($dst, true);
imagecopyresampled($dst, $src, 0,0,0,0, 200,200, imagesx($src), imagesy($src));
imagepng($dst, 'logo_resized.png');
imagedestroy($src); imagedestroy($dst);
?>
<?php
function resizeProportional(string $srcPath, string $dstPath, int $maxW, int $maxH): bool
{
$info = getimagesize($srcPath);
if (!$info) return false;
[$srcW, $srcH, $type] = $info;
$scale = min($maxW/$srcW, $maxH/$srcH);
$dstW = (int)($srcW * $scale);
$dstH = (int)($srcH * $scale);
$create = ['imagecreatefromjpeg','imagecreatefrompng','imagecreatefromgif','imagecreatefromwebp'][$type-1] ?? null;
$output = ['imagejpeg','imagepng','imagegif','imagewebp'][$type-1] ?? null;
if (!$create || !$output) return false;
$src = $create($srcPath);
$dst = imagecreatetruecolor($dstW, $dstH);
if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
imagealphablending($dst, false);
imagesavealpha($dst, true);
$transparent = imagecolortransparent($src);
if ($transparent >= 0) {
$rgb = imagecolorsforindex($src, $transparent);
$newTransparent = imagecolorallocatealpha($dst, $rgb['red'], $rgb['green'], $rgb['blue'], 127);
imagefill($dst, 0, 0, $newTransparent);
imagecolortransparent($dst, $newTransparent);
}
}
imagecopyresampled($dst, $src, 0,0,0,0, $dstW,$dstH, $srcW,$srcH);
$result = $output($dst, $dstPath, $type == IMAGETYPE_JPEG ? 90 : null);
imagedestroy($src); imagedestroy($dst);
return $result;
}
?>
<?php
// 文字水印
function addTextWatermark($src, $text, $font, $size, $color, $x, $y, $dst) {
$im = imagecreatefromjpeg($src);
$c = imagecolorallocate($im, ...$color);
imagettftext($im, $size, 0, $x, $y, $c, $font, $text);
imagejpeg($im, $dst);
imagedestroy($im);
}
// 圖片水印
function addImageWatermark($src, $watermark, $x, $y, $dst) {
$im = imagecreatefromjpeg($src);
$wm = imagecreatefrompng($watermark);
imagecopy($im, $wm, $x, $y, 0, 0, imagesx($wm), imagesy($wm));
imagejpeg($im, $dst);
imagedestroy($im); imagedestroy($wm);
}
?>
處理大圖或批量處理時,務必及時 `imagedestroy()`;若遇到「Allowed memory size exhausted」,可臨時調大 `memory_limit` 或分塊處理。