Skip to content

Instantly share code, notes, and snippets.

@lomboboo
Last active November 30, 2021 13:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lomboboo/08da569edf789f94aa8fa0b598420002 to your computer and use it in GitHub Desktop.
Save lomboboo/08da569edf789f94aa8fa0b598420002 to your computer and use it in GitHub Desktop.
PHP add watermark with centered diagonal text
<?php
// recursive search by pattern
function rsearch($folder, $pattern) {
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
$files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
$fileList = array();
foreach($files as $file) {
$fileList = array_merge($fileList, $file);
}
return $fileList;
}
function addWatermark($image)
{
$im = imagecreatefromjpeg($image);
$font = dirname(__FILE__) . '/comic.ttf';
$text = 'some text';
$angle = 45; // rotate 45 degrees
$transparency = 0.2;
$text_opacity = 100 - $transparency * 100;
$white = imagecolorallocatealpha($im, 255, 255, 255, $text_opacity);
$shadow = imagecolorallocatealpha($im, 0, 0, 0, 95);
$width = imagesx($im);
$font_size = $width / 15; // font size relative to image width
$height = imagesy($im);
$centerX = $width / 2;
$centerY = $height / 2;
// Get size of text
list($left, $bottom, $right, , , $top) = imageftbbox($font_size, $angle, $font, $text);
// Determine offset of text
$left_offset = ($right - $left) / 2;
$top_offset = ($bottom - $top) / 2;
// Generate coordinates
$x = $centerX - $left_offset;
$y = $centerY + $top_offset;
imagettftext($im, $font_size, $angle, $x + 3, $y + 3, $shadow, $font, $text); // add shadow
imagettftext($im, $font_size, $angle, $x, $y, $white, $font, $text); // add text
imagejpeg($im, $image); // override image with watermark image
imagedestroy($im); // free memory
}
$dirname = './directory/img/';
$images = rsearch($dirname, "/.*-(?:large|medium)_default\.jpg/");
foreach ($images as $filename) {
addWatermark($filename);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment