Search code examples
phpimage-processinggdwatermark

Watermarking centered instead of top right


I'm using a php function that creates a watermarkon the top right of an image.

Here's the code :

<?php
function watermarking($source, $watermark, $save = NULL, $width = null, $height = null) {
    $watermark = @imagecreatefrompng($watermark)
        or exit("Impossible d'ouvrir le fichier (watermark).");

    imageAlphaBlending($watermark, false);
    imageSaveAlpha($watermark, true);

    $imageString = @file_get_contents($source)
        or exit("Impossible d'ouvrir le fichier (image).");
    $image = @imagecreatefromstring($imageString)
        or exit("Format de fichier (image) inconnu.");

    $imageWidth = imageSX($image);
    $imageHeight = imageSY($image);

    if (!($width)) {
        $watermarkWidth = imageSX($watermark);
    } else {
        $watermarkWidth = $width;
    }

    if (!($height)) {
        $watermarkHeight = imageSY($watermark);
    } else {
        $watermarkHeight = $height;
    }

    $coordinateX = ($imageWidth - 15) - ($watermarkWidth);
    $coordinateY = ($imageHeight - 15) - ($watermarkHeight);

    imagecopy($image, $watermark, $coordinateX, $coordinateY, 0, 0, $watermarkWidth, $watermarkHeight);

    if (!($save)) {
        header('Content-Type: image/jpeg');
    }   

    imagejpeg ($image, $save, 100);

    imagedestroy($image);
    imagedestroy($watermark);

    if (!($save)) {
        exit;
    }
}
?>

This function adds a watermark to the top right, but i want to centre it on the image instead.

How to do it ?

Thanks


Solution

  • Update the coordinate variables as such

    $coordinateX = ($imageWidth - $watermarkWidth) / 2;
    $coordinateY = ($imageHeight - $watermarkHeight) / 2;