PHP

How to add watermark to all images in a folder and its sub folders

This is a continuous tutorial to my earlier tutorial about How to add watermark to all images in a folder. In this tutorial, you will learn how to add watermark to all images in a folder and all its sub folders.

Here is the sample code:

<?php
//Source folder where all images are placed
$source="source";

//Destination folder where all images with watermark will be copied
$destination="destination";

//Creating an image object of watermark image
$watermark=imagecreatefrompng("watermark.png");

//Margin of watermark from right and bottom of the main image
$margin_right=10;
$margin_bottom=10;

//Height ($sy) and Width ($sx) of watermark image
$sx=imagesx($watermark);
$sy=imagesy($watermark);

//recursive function to get the structure of the source directory
function dirToArray($dir) {

   $result = array();

   $cdir = scandir($dir);
   foreach ($cdir as $key => $value)
   {
      if (!in_array($value,array(".","..")))
      {
         if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
         {
            $result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
         }
         else
         {
           	$result[] = $value;
         }
      }
   }

   return $result;
}

$structure=dirToArray($source);

$images=array();

//recursive function to find list of all files in the source directory
function fileFinder($structure,$path){
  $result="";
  global $images;
  foreach($structure as $key=>$value){
    if(is_array($value))
      fileFinder($value,$path.'/'.$key);
    else
      $images[]=$path.'/'.$value;
  }
}

fileFinder($structure,"");

foreach($images as $image){
  // find the list directories to be created in the destination directory
  $parts=explode("/",$image);
  $parts2=array_pop($parts);
  $parts3=array_shift($parts);
  $directories=implode("/",$parts);
  createPath($destination.'/'.$directories);
  
  //Create image object of main image
  $img=imagecreatefromjpeg($source.$image);

  //Copying watermark image into the main image
  imagecopy($img, $watermark, imagesx($img) - $sx - $margin_right, imagesy($img) - $sy - $margin_bottom, 0, 0, $sx, $sy);

  //Saving the merged image into the destination folder
  imagejpeg($img, $destination.'/'.$image,100);

  //Destroying the main image object
  imagedestroy($img);
}

function createPath($path) {
    if (is_dir($path)) return true;
    $prev_path = substr($path, 0, strrpos($path, '/', -2) + 1 );
    $return = createPath($prev_path);
    return ($return && is_writable($prev_path)) ? mkdir($path) : false;
}

//Destroying watermark image object
imagedestroy($watermark);

 


About the author

Sujeet Kr Singh