Watermark script in php

How to tag your published photos on the Internet? There are many ways to do this through image processing software. I needed a simple automatic system: I put my photos in a directory (In), I run a script, the marked photos are created in an output directory (Out) with the same name. I do not have to size anything for each photo.

In practice, we have an “In” directory for photos to be processed, an “Out” directory for the processed photos, the Logo to embed and the PHP script. In addition to PHP, you need ImageMagick installed. The incrustation is light at 5%, it is possible to modify this value to obtain a more or less marked encrustation.

<?php
$dirIn = "In";
$dirOut = "Out";
$logo = "Logo.png";
$tmpFile = "tmp.png";
 
if ($dh = opendir($dirIn)) {
  while (($file = readdir($dh)) !== false) {
    $fileName = $dirIn."/".$file;
    if (!is_file($fileName)) {
      continue;
    }
    echo "File : $file : type : " . filetype($fileName) . "\n";
    list($width, $height, $type, $attr) = getimagesize($fileName);
 
    // Resize logo
    $cmd = "convert $logo -geometry '$width"."x"."$height' $tmpFile";
    exec($cmd);
    echo "> $cmd\n";
 
    // Put the watermark
    $cmd = "composite -watermark 5% -gravity center $tmpFile $fileName $dirOut/$file";
    exec($cmd);
    echo "> $cmd\n";
  }
  closedir($dh);
}
@unlink($tmpFile);


I did not try this script on Windows, but it should not be a problem.

Related Posts