Hack: Automatically Watermark Every Image You Upload to WordPress

Putting some text on every image you use on your blog can be a pain if you do it manually. It would be so great if WordPress just did this automatically. Here is one, pretty simple, way to do it. You can see the result in the image below.

By filtering the wp_handle_upload hook we can grab the image before WordPress does, write some text on to it, and then save the image so WordPress processes an image with the text watermark instead of the original. You can add this to your functions.php or custom plugin.

add_filter('wp_handle_upload', 'wpfilter_handle_upload');
function wpfilter_handle_upload($resource) {
	$text = 'WPWombat.com';
	
	$image = imagecreatefromstring(file_get_contents($resource['file']));
	list($width, $height)= getimagesize($resource['file']);
	
	$white = imagecolorallocate($image, 255, 255, 255);
	$black = imagecolorallocate($image, 0, 0, 0);
	$font = '../wp-content/themes/twentynineteen-child/OpenSans-Regular.ttf';
	
	imagettftext($image, 20, 0, 11, $height-9, $black, $font, $text);
	imagettftext($image, 20, 0, 10, $height-10, $white, $font, $text);
	
	imagejpeg($image, $resource['file']);
	imagedestroy($image);

	return $resource;
}

A few notes. I use imagecreatefromstring so that the function handles any type of image, and you don’t have to worry about the file type. Then I uploaded the free Google OpenSans-Regular.ttf font to my child theme directory and put in the path you see there. The ../ at the start is because upload.php is down in wp-admin, so the path needs to go up from there. Or, you can use get_template_directory() if you like instead of a path. You can use whatever .ttf font file you like, of course.

I print the text on to the image twice, using black and then white, with a slight position change. This creates a shadow so the text looks OK on light or dark images. Then I write out the image with imagejpeg, which means this also converts png uploads to jpegs. So you may want to add more logic there if you want to maintain the image format.

The position of the text should be bottom left. You’ll need to do more calculations if you want it to be bottom right. Also, the size is fixes and unrelated to the image size, so more calculations there if you want to size the text to fit the image width in a relative manner. I wanted to keep this function as simple as possible so anyone can use it as a jumping-off point to create something specific.

Leave a Reply

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