Current Location: Home> Latest Articles> How to add watermark text after imagegetclip cropping? One article teaches you how to do it

How to add watermark text after imagegetclip cropping? One article teaches you how to do it

gitbox 2025-05-28

1. What is imagegetclip?

imagegetclip is not a built-in PHP function, it is generally a user-defined function for image cropping. In order to realize the functions of this article, we simply define an imagegetclip() function, which aims to cut out a rectangular area from the source diagram.

2. Realize the complete process of cropping and adding watermarks

The complete steps are as follows:

  1. Load the source map;

  2. Crop the image;

  3. Add text watermark;

  4. Output or save the image.

Below is a complete code example.

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

// Example:Processing images
$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.netExclusive');

header('Content-Type: image/jpeg');
imagejpeg($clip_with_watermark);
imagedestroy($clip_with_watermark);
?>

3. Explanation

  • The imagegetclip() function clips the specified area from the original image;

  • addTextWatermark() function to add watermark text;

  • The basic fonts added using imagestring() . If you need to use custom fonts and styles, it is recommended to use imagettftext() ;

  • Remote images are downloaded to a temporary directory through file_get_contents() ;

  • Note that the server must enable GD extension.

4. Supplement: Use custom fonts to beautify watermark text

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

This code uses TTF font to achieve more beautiful watermark text. Ensure that the font path is valid and supports Chinese or required character sets.