Skip to content

Instantly share code, notes, and snippets.

@janzikan
Last active October 6, 2015 12:38
Show Gist options
  • Save janzikan/2994846 to your computer and use it in GitHub Desktop.
Save janzikan/2994846 to your computer and use it in GitHub Desktop.
PHP: Add watermark to image
/**
* Create JPEG image with watermark.
* @param string $sourceImage path to source JPEG image
* @param string $watermark path to watermark in GIF format
* @param string $targetImage path to final JPEG image file
* @param int $transparency watermark transparency (0 transparent - 100 solid)
* @param int $quality quality of final image (0-100)
* @param int offsetX offset of watermark from edge in horizontal direction
* @param int $offsetY offset of watermark from edge in vertical direction
* @param string $alignX alignment of watermark in horizontal direction (left, middle, right)
* @param string $alignY allignment of watermark in vertical direction (top, middle, bottom)
* @return bool
*/
function addWatermark($sourceImage, $watermark, $targetImage, $transparency = 100, $quality = 80, $offsetX = 10, $offsetY = 10, $alignX = 'right', $alignY = 'bottom')
{
// Obtain image from given source file.
if (!$image = @imagecreatefromjpeg($sourceImage))
{
return false;
}
if (!$imageWatermark = @imagecreatefromgif($watermark))
{
return false;
}
// Get dimensions of source image.
list($imageWidth, $imageHeight) = getimagesize($sourceImage);
// Get dimensions of watermark.
list($watermarkWidth, $watermarkHeight) = getimagesize($watermark);
// Supported horizontal and vertical alignments.
$alignmentsX = array('left', 'middle', 'right');
$alignmentsY = array('top', 'middle', 'bottom');
// Set default horizontal and vertical alignments if the parameters are incorrect.
if (!in_array($alignX, $alignmentsX))
{
$alignX = 'right';
}
if (!in_array($alignY, $alignmentsY))
{
$alignY = 'bottom';
}
// Calculate horizontal position of watermark.
if ($alignX == 'middle')
{
$posX = $imageWidth/2 - $watermarkWidth/2 + $offsetX;
}
elseif ($alignX == 'left')
{
$posX = $offsetX;
}
elseif ($alignX == 'right')
{
$posX = $imageWidth - $watermarkWidth - $offsetX;
}
// Calculate vertical position of watermark.
if ($alignY == 'middle')
{
$posY = $imageHeight/2 - $watermarkHeight/2 + $offsetY;
}
elseif ($alignY == 'top')
{
$posY = $offsetY;
}
elseif ($alignY == 'bottom')
{
$posY = $imageHeight - $watermarkHeight - $offsetY;
}
// Add watermark to the image.
imagecopymerge($image, $imageWatermark, $posX, $posY, 0, 0, $watermarkWidth, $watermarkHeight, $transparency);
// Create final image.
imagejpeg($image, $targetImage, $quality);
// Free up the memory.
imagedestroy($image);
imagedestroy($imageWatermark);
return true;
}
/**
* Example:
* addWatermark('image.jpg', 'watermark.gif', 'final.jpg');
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment