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 字体实现更漂亮的水印文字。确保字体路径有效且支持中文或所需字符集。