I had a work, when the customer wanted to add watermark to the uploaded images. I tried some solutions, and finally found that one, what works well. What we need for this task? A png image what contains the watermark image. This must be transparent background, and semi transparent image, otherwise the result won’t be watermark, just an image what merged with another. We need a form too, to upload the image, and a script, what process the request, and add the watermark to the uploaded image.
Here provide only the php script, what process the file. Of course, we need a page, what contains the form, to posts the image to the server.
First a small function, what returns the extension of the uploaded file.
function getExtension($str)
{$i = strrpos($str,”.”);
if (!$i) { return “”; }
$l = strlen($str) – $i;
$ext = substr($str,$i+1,$l);
return $ext;}
$saved_image_name=$_FILES['image_file']['name'];
$img_info=$_GET['img_info'];
if ($saved_image_name)
{$filename = stripslashes($_FILES['image_file']['name']);
$extension = getExtension($filename);
$extension = strtolower($extension);
if (($extension != “jpg”) && ($extension != “jpeg”) && ($extension != “png”))
{echo “You can upload only JPG or PNG files!”;
}
else
{$size=filesize($_FILES['image_file']['tmp_name']);
if ($size > MAX_SIZE*1024)
{echo “The file is too large!”;
}
else
{$image_name=time().’.png’; // we create a unique name to save the file
$uploadsDirectory = ‘/upload_folder/’;
$newname=$uploadsDirectory.$image_name;$uploadedfile = $_FILES['image_file']['tmp_name'];
if($extension==”jpg” || $extension==”jpeg” )
{$src = imagecreatefromjpeg($uploadedfile);
}
else if($extension==”png”)
{$src = imagecreatefrompng($uploadedfile);
}
list($width,$height)=getimagesize($uploadedfile);$wmimage=get_option(‘watermark’,”);
if ($wmimage!=”")
{$watermark = imagecreatefrompng($wmimage);
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$dest_x = 5;
$dest_y = 5;
imagecopy($src, $watermark, $dest_x,$dest_y, 0, 0, $watermark_width, $watermark_height);
imagepng($src,$newname,100);
@imagedestroy($src);
@imagedestroy($watermark);}
}
}
}
This script opens the uploaded and the watermark image, then – with the imagecopy function – copies the watermark onto the top of the original image. The $dest_x and $dest_y gives the starting coordinates, and can contains negativ values too.
This solution saves the images with watermark to the upload folder, so if you want to keep the original images too, you have to make a copy before you merge them with the watermark.



















