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:

//Source folder where all images are placed

//Destination folder where all images with watermark will be copied

//Creating an image object of watermark image

//Margin of watermark from right and bottom of the main image

//Height ($sy) and Width ($sx) of watermark image

//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);
           	$result[] = $value;

   return $result;



//recursive function to find list of all files in the source directory
function fileFinder($structure,$path){
  global $images;
  foreach($structure as $key=>$value){


foreach($images as $image){
  // find the list directories to be created in the destination directory
  //Create image object of main 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

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


About the author

Sujeet Kr Singh