Skip to content

Instantly share code, notes, and snippets.

@kayesshu
Created September 12, 2015 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kayesshu/6a5c5fc329e459ed96a3 to your computer and use it in GitHub Desktop.
Save kayesshu/6a5c5fc329e459ed96a3 to your computer and use it in GitHub Desktop.
How to add a watermark image as a transparent layer to an existing image in PHP using GD
function generate_watermarked_image($originalFileContents, $originalWidth, $originalHeight, $paddingFromBottomRight = 0, $watermarkFileLocation = 'logo.png') {
$watermarkImage = imagecreatefrompng($watermarkFileLocation);
$watermarkWidth = imagesx($watermarkImage);
$watermarkHeight = imagesy($watermarkImage);
$originalImage = imagecreatefromstring($originalFileContents);
$destX = $originalWidth - $watermarkWidth - $paddingFromBottomRight;
$destY = $originalHeight - $watermarkHeight - $paddingFromBottomRight;
// creating a cut resource
$cut = imagecreatetruecolor($watermarkWidth, $watermarkHeight);
// copying that section of the background to the cut
imagecopy($cut, $originalImage, 0, 0, $destX, $destY, $watermarkWidth, $watermarkHeight);
// placing the watermark now
imagecopy($cut, $watermarkImage, 0, 0, 0, 0, $watermarkWidth, $watermarkHeight);
// merging both of the images
imagecopymerge($originalImage, $cut, $destX, $destY, 0, 0, $watermarkWidth, $watermarkHeight, 100);
return $originalImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment