Use imagecopymerge() to watermark an image with PHP

June 14, 2014 | Last tested: May 2015 | 1495 views | Comments

Dynamically set the opacity of the watermark image in PHP using the function imagecopymerge().

For example.

Resource images:

  1. The waterwark PNG image, created with Photoshop. The text opacity is 100%. testLogo.png
  2. JPG image to be watermarked. create-a-dark-forest-scene-photo-manipulation.jpg (used with permission) Source link.

 

Set the opacity of the watermark image to 50%.

//set the source image (foreground)
$sourceImage = 'testLogo.png';

//set the transparency of the source image
$srcTransparency = 50; //the higher the clearer, max is 100

//set the destination image (background)
$destImage = 'create-a-dark-forest-scene-photo-manipulation.jpg';

//get the size of the source image, needed for imagecopymerge()
list($srcWidth, $srcHeight) = getimagesize($sourceImage);

//create a new image from the source image
$src = imagecreatefrompng($sourceImage);

//create a new image from the destination image
$dest = imagecreatefromjpeg($destImage);

//set the x and y positions of the source image on top of the destination image
$src_xPosition = 10; //10 pixels from the left
$src_yPosition = 10; //10 pixels from the top

//set the x and y positions of the source image to be copied to the destination image
$src_cropXposition = 0; //do not crop at the side
$src_cropYposition = 0; //do not crop on the top

/*
 * get the index of the color of a pixel of the source image (imagecolorat),
 * and define a color as transparent (imagecolortransparent)
 */
imagecolortransparent($src,imagecolorat($src,0,0));
						
//merge the source and destination images
imagecopymerge($dest,$src,$src_xPosition,$src_yPosition,$src_cropXposition,$src_cropYposition,$srcWidth,$srcHeight,$srcTransparency);

//output the merged images to a file
/*
 * '100' is an optional parameter,
 * it represents the quality of the image to be created,
 * if not set, the default is about '75'
 */
imagejpeg($dest,'use-imagecopymerge()-to-watermark-an-image-with-php.jpg',100);

//destroy the source image
imagedestroy($src);

//destroy the destination image
imagedestroy($dest);

Result.

Please mouse over here to view the image.

 

Set the opacity to 75%.

  1. Just change this line.
    
    $srcTransparency = 50;
    

    To this.
    
    $srcTransparency = 75;
    

Result.

Please mouse over here to view the image.

 

Make the opacity to 100%.

  1. Just update this line.
    
    $srcTransparency = 50;
    

    With this.
    
    $srcTransparency = 100;
    

Result.

Please mouse over here to view the image.