In a previous article, I demonstrated how one could use PHP to dynamically add watermarks to images. Implementing the solution I presented in that article required you to change your image links to something like this:
<img src="watermark.php?image=sample1.jpg&watermark=watermark.png" />In this article, I will show you how you can easily watermark all images in a certain directory without changing your links to point to a .php file.
Solution Details
Let’s say the images you want to watermark are kept in a sub directory called “gallery” right below your domain folder. At this point, you will have to upload the watermarking script (watermark.php) and the watermark image (watermark.png) to that exact folder and create an .htaccess file containing the following two lines of code:
RewriteEngine on RewriteRule ^(.*\.(gif|jp?g|png))$ /gallery/watermark.php?image=$1&watermark=watermark.png [NC]
By using the RewriteRule directory, you are telling the web server that image requests shall be processed by the “watermark.php” script file, as opposed to serving the images directly to the browser. The “watermark.php” script then places the “watermark.png” as a watermark on the requested image. After completing the .htaccess file, it must be uploaded (in ASCII mode) to the “gallery” directory.
Download Sample Files
If you wish to play around a bit with my sample code, I have created a zip file that contains all the necessary files for you to do so.