Watermark An Image

Submitted by:Jhon Smith

Date added:16 March, 2011

Category:PHP

Take an image, and put a water mark on top of it.
Note that you can only use this function once per page.

Tags: watermark script , php watermark

Code Snippet:

<?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.
?>
 
 

Comments