Adding PNG Watermarks to JPEGs with PHP
This took up a good chunk of my afternoon. I have a client who wants to upload JPEG images to his website and have them automatically resized and watermarked with copyright information to discourage image theft. Resizing is a piece of cake — I’ve done that before — but getting the alpha transparency of a 24-bit PNG to overlay correctly was maddening.
It turns out that the solution is actually really simple. The code is below:
$photo = imagecreatefromjpeg("original.jpg");
$watermark = imagecreatefrompng("watermark.png");
// This is the key. Without ImageAlphaBlending on, the PNG won't render correctly.
imagealphablending($photo, true);
// Copy the watermark onto the master, $offset px from the bottom right corner.
$offset = 10;
imagecopy($photo, $watermark, imagesx($photo) - imagesx($watermark) - $offset, imagesy($photo) - imagesy($watermark) - $offset, 0, 0, imagesx($watermark), imagesy($watermark));
// Output to the browser - please note you should save the image once and serve that instead on a production website.
header("Content-Type: image/jpeg");
imagejpeg($photo);
Note: It’s a bad idea to do this on the fly for each visitor. I strongly recommend watermarking an image once and then using that image for your website.

