December 2, 2008
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:
1$photo = imagecreatefromjpeg('original.jpg'); 2$watermark = imagecreatefrompng('watermark.png'); 3 4// This is the key - without ImageAlphaBlending on, the PNG won't render correctly. 5imagealphablending($photo, true); 6 7// Copy the watermark onto the master, $offset px from the bottom right corner. 8$offset = 10; 9imagecopy(10 $photo,11 $watermark,12 imagesx($photo) - imagesx($watermark) - $offset,13 imagesy($photo) - imagesy($watermark) - $offset,14 0,15 0,16 imagesx($watermark),17 imagesy($watermark)18);19 20// Output to the browser - note that on a production website, you should save the image to the filesystem and serve it directly.21header('Content-Type: image/jpeg');22imagejpeg($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.