imagegetclip不是PHP內置函數,它一般是用戶自定義的一個用於圖像裁剪的函數。為了實現本文的功能,我們簡單定義一個imagegetclip()函數,其目的是從源圖中裁剪出一個矩形區域。
完整步驟如下:
加載源圖;
裁剪圖像;
添加文字水印;
輸出或保存圖像。
下面是完整的代碼示例。
<?php
function imagegetclip($src_path, $x, $y, $width, $height) {
$src = imagecreatefromjpeg($src_path);
$clip = imagecreatetruecolor($width, $height);
imagecopy($clip, $src, 0, 0, $x, $y, $width, $height);
return $clip;
}
function addTextWatermark($image, $text, $fontSize = 12, $color = [255, 255, 255], $x = 10, $y = 20) {
$textColor = imagecolorallocate($image, $color[0], $color[1], $color[2]);
imagestring($image, $fontSize, $x, $y, $text, $textColor);
return $image;
}
// 示例:處理圖像
$source_image = 'https://gitbox.net/images/sample.jpg';
$temp_path = '/tmp/temp.jpg';
file_put_contents($temp_path, file_get_contents($source_image));
$clip = imagegetclip($temp_path, 100, 100, 300, 200);
$clip_with_watermark = addTextWatermark($clip, 'gitbox.net專屬');
header('Content-Type: image/jpeg');
imagejpeg($clip_with_watermark);
imagedestroy($clip_with_watermark);
?>
imagegetclip()函數從原圖中裁剪指定區域;
addTextWatermark()函數添加水印文字;
使用imagestring()添加的是基本字體,如果需要使用自定義字體和样式,建議使用imagettftext() ;
遠程圖片通過file_get_contents()下載到臨時目錄使用;
注意服務端必須啟用GD 擴展。
imagettftext($image, 16, 0, 10, 30, $textColor, '/path/to/font.ttf', 'gitbox.net專屬');
這段代碼用TTF字體實現更漂亮的水印文字。確保字體路徑有效且支持中文或所需字符集。