当前位置: 首页> 最新文章列表> 如何在图像裁剪后通过imagegetclip实现文字水印添加

如何在图像裁剪后通过imagegetclip实现文字水印添加

gitbox 2025-05-28

1. 什么是 imagegetclip?

imagegetclip 不是PHP内置函数,它一般是用户自定义的一个用于图像裁剪的函数。为了实现本文的功能,我们简单定义一个imagegetclip()函数,其目的是从源图中裁剪出一个矩形区域。

2. 实现裁剪加水印的完整流程

完整步骤如下:

  1. 加载源图;

  2. 裁剪图像;

  3. 添加文字水印;

  4. 输出或保存图像。

下面是完整的代码示例。

<?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);
?>

3. 说明

  • imagegetclip() 函数从原图中裁剪指定区域;

  • addTextWatermark() 函数添加水印文字;

  • 使用 imagestring() 添加的是基本字体,如果需要使用自定义字体和样式,建议使用 imagettftext()

  • 远程图片通过 file_get_contents() 下载到临时目录使用;

  • 注意服务端必须启用 GD 扩展。

4. 补充:使用自定义字体美化水印文字

imagettftext($image, 16, 0, 10, 30, $textColor, '/path/to/font.ttf', 'gitbox.net专属');

这段代码用 TTF 字体实现更漂亮的水印文字。确保字体路径有效且支持中文或所需字符集。