Put A Watermark On Top Of An Image Using PHP
Why put up with manually embedding watermarks on your images when you can have it done for you automatically using JavaScript, or in this case, PHP? This PHP snippet will make use of a image file (PNG) that you’ll create and supply, and place it on top of the photo you want watermarked at a pre-defined (e.g. bottom-left, upper-right, etc.) or exact position (by pixels).
<?php function watermark($file, $watermark, $pos = null, $x = 0, $y = 0){ $details = getimagesize($file); $wDetails = getimagesize($watermark); if(!is_null($pos)){ switch($pos){ case TOP_LEFT: $x = 0; $y = 0; break; case TOP_RIGHT: $x = $details[0] - $wDetails[0]; $y = 0; break; case BOTTOM_LEFT: $x = 0; $y = $details[1] - $wDetails[1]; break; case BOTTOM_RIGHT: $x = $details[0] - $wDetails[0]; $y = $details[1] - $wDetails[1]; break; case CENTER: $x = round(($details[0] - $wDetails[0])/2); $y = round(($details[1] - $wDetails[1])/2); break; } } switch($details['mime']){ case 'image/jpeg':$im = imagecreatefromjpeg($file);break; case 'image/gif':$im = imagecreatefromgif($file);break; case 'image/png':$im = imagecreatefrompng($file);break; } switch($wDetails['mime']){ case 'image/jpeg':$newWater = imagecreatefromjpeg($watermark);break; case 'image/gif':$newWater = imagecreatefromgif($watermark);$colorTransparent = imagecolortransparent($newWater);imagefill($newWater, 0, 0, $colorTransparent);imagecolortransparent($newWater, $colorTransparent);break; case 'image/png':$newWater = imagecreatefrompng($watermark);imagealphablending($newWater, false);imagesavealpha($newWater,true);break; } imagecopyresampled($im, $newWater, $x, $y, 0, 0, $wDetails[0], $wDetails[1], $wDetails[0], $wDetails[1]); // Output the image switch($details['mime']){ case 'image/jpeg':header('Content-type: image/jpeg');imagejpeg($im);break; case 'image/gif':header('Content-type: image/gif');imagegif($im);break; case 'image/png':header('Content-type: image/png');imagepng($im);break; } // Free up memory imagedestroy($im); } // Watermark using only the defaults watermark('girl.jpg','watermark.png'); // Watermark using a pre-defined position // Valid values: TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT, CENTER watermark('girl.jpg','watermark.png', BOTTOM_RIGHT); // Watermark using an exact position watermark('girl.jpg','watermark.png', null, 150, 150); // Note that you can only use this function once per page. // If it is used more than one time, the image that will be displayed // will be the first function called. ?>
1 Comment
http://www.atomwebhosting.com/vps.htm
01.16.2013
Hello! I’ve been following your blog for a while now and finally got the bravery to go ahead and give you a shout out from Dallas Texas! Just wanted to mention keep up the good work!
There are no trackbacks to display at this time.