Watermark Image

Last updated on November 29th, 2022 at 03:51 pm

This is a very simple script that watermarks an image with a PNG file using PHP. Just save this PHP file as .php and run this in your website or localhost.

Make sure the path specified for your image and the watermark png is correct.

In the below script I am going to watermark an image named “mypic.jpg” with my website logo with name “logo.png

Update this part of code with your image files : We are just passing the main image and the logo file to the watermark function.


If you have time check our tutorial on watermarking images using PHP and GD Library.

Complete code

//just save this file as <sumname>.php and run this in your website or locahost//make sure the path specified for your image and the watermark png is correct
function watermark($sourcefile, $watermarkfile) {
# $sourcefile    = Filename of the picture to be watermarked.
# $watermarkfile   = Filename of the 24-bit PNG watermark file.
//Get the resource ids of the pictures
$watermarkfile_id   = imagecreatefrompng($watermarkfile);
imageAlphaBlending($watermarkfile_id, false);
imageSaveAlpha($watermarkfile_id, true);
$fileType = strtolower(substr($sourcefile, strlen($sourcefile)-3));
switch($fileType) {
$sourcefile_id = imagecreatefromgif($sourcefile);
$sourcefile_id = imagecreatefrompng($sourcefile);
$sourcefile_id = imagecreatefromjpeg($sourcefile);
//Get the sizes of both pix
$sourcefile_width = imageSX($sourcefile_id);
$sourcefile_height = imageSY($sourcefile_id);
$watermarkfile_width = imageSX($watermarkfile_id);
$watermarkfile_height = imageSY($watermarkfile_id);
$dest_x=$s_width ;
// if a gif, we have to upsample it to a truecolor image
if($fileType == "gif") {
// create an empty truecolor container
$tempimage = imagecreatetruecolor($sourcefile_width, $sourcefile_height);
// copy the 8-bit gif into the truecolor image
imagecopy($tempimage, $sourcefile_id, 0, 0, 0, 0, $sourcefile_width, $sourcefile_height);// copy the source_id int
$sourcefile_id = $tempimage;
imagecopy($sourcefile_id, $watermarkfile_id, $dest_x, $dest_y, 0, 0, $watermarkfile_width, $watermarkfile_height);
//Create a jpeg out of the modified picture
switch($fileType) {
// remember we do not need gif any more, so we use only png or jpeg.
// See the code above to see how we handle gifs
header("Content-type: image/png");
imagepng ($sourcefile_id);
header("Content-type: image/jpg");
imagejpeg ($sourcefile_id);
echo "Test";


Note:-This tutorial was originally posted on Jul 13, 2009 and Bugs fixed with Demo added on May 20, 2016. Updated again on May 2nd 2022

Leave a Reply

Your email address will not be published. Required fields are marked *