How to watermark an image in wordpress with WPThumb

After spending a lot of time looking for the perfect solution to place a watermark on specific WordPress images I think it’s worth sharing.

I need a watermark on a specific image size. I don’t want to use it on the small thumbnails, so it’s not useful to render it on upload.

My solution is to use WP-Thumb and generate the images on demand (of course caching is possible).

In this case I use Advanced Custom Fields to upload the image so I have an array with image informations:

    [id] => 43
    [alt] => 
    [title] => imagetitle
    [description] => 
    [url] =>
    [width] => 640
    [height] => 480

in my theme there is an image called watermark.png which should be placed on the top right of the my resized image. I use this function in my functions.php (the image size is theme specific)

function watermark_image($pic){

   $image = new WP_Thumb( $pic['url'], array( 'width' => $w, 'height' => $h, 'cache' => false, 'return' => 'path', 'watermarking_options' => array(
     'mask' => get_template_directory_uri().'/images/watermark.png',
        'position' => 'top,right',
     'padding' => 0
   ) ) );

  return $image->getCacheFileUrl();

and this is how you call it:

$pic = get_field('picture');
echo '<img  src="'.watermark_image( $pic ).'" alt="'.$pic['alt'].'" title="'.$pic['title'].'">';