Hack: Automatically Watermark Your Images With a Transparent Overlay

I previous showed you how to place some text over an image when you added it to your Media library. But you may want more than plain text. Here is a way to use a transparent PNG file instead. This example show some text and a logo, with a white drop shadow to make the dark watermark stand out.

First, you create a transparent PNG. It will be scaled to fill the width of the image, and then align to the bottom of the image. So if you want your watermark to take up the bottom right corner and go from the center to the right edge, then make a wide thin image, like 1000×60 and put your graphics on the right half of that.

Here is the function, that can be put in your functions.php or custom plugin.

add_filter('wp_handle_upload', 'wpfilter_add_png_watermark');
function wpfilter_add_png_watermark($resource) {
	$watermark = '../wp-content/themes/twentynineteen-child/WombatWatermark.png';
	$wm = imagecreatefrompng($watermark);
	list($wmwidth, $wmheight)= getimagesize($watermark);
	
	$image = imagecreatefromstring(file_get_contents($resource['file']));
	list($width, $height)= getimagesize($resource['file']);
	
	$scale = $width/$wmwidth;
	
	imagecopyresampled($image, $wm, 0, $height-$wmheight*$scale, 0, 0, $wmwidth*$scale, $wmheight*$scale, $wmwidth, $wmheight);
	
	imagejpeg($image, $resource['file']);
	imagedestroy($image);

	return $resource;
}

Note that the path to the image needs to be changed to the path and filename of the image you want. The script originates from wp-admin when you upload media. That’s why there is a ../ at the start to go up a level.

Both the watermark image and the uploaded image are put into variables. I use imagecreatefromstring so it handles any image type. But note that at the end I write out a jpeg. So you’ll want to add some more functionality there to write out a png if the image is a png, a jpeg if it is a jpeg, etc.

I’m scaling the watermark so it fits the width of the image. Then those calculations in imagecopyresampled keep the proportions correct. You might as well make the watermark image nice and big so it looks good on large and small photos.

Leave a Reply

Your email address will not be published. Required fields are marked *