Adding watermarks to images using alpha channels

Example #1 Adding watermarks to images using alpha channels

<?php
// Load the stamp and the photo to apply the watermark to
$stamp imagecreatefrompng('stamp.png');
$im imagecreatefromjpeg('photo.jpeg');

// Set the margins for the stamp and get the height/width of the stamp image
$marge_right 10;
$marge_bottom 10;
$sx imagesx($stamp);
$sy imagesy($stamp);

// Copy the stamp image onto our photo using the margin offsets and the photo 
// width to calculate positioning of the stamp. 
imagecopy($im$stampimagesx($im) - $sx $marge_rightimagesy($im) - $sy $marge_bottom00imagesx($stamp), imagesy($stamp));

// Output and free memory
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
Adding watermarks to images using alpha channels
This example is a common way to add watermarks and stamps to photos and copyrighted images. Note that the presence of an alpha channel in the stamp image as the text is anti-aliased. This is preserved during copying.

Коментарии

Автор:
function addWatermark($sourceImage, $watermarkImage, $outputPath) {
    // Загружаем исходное изображение и водяной знак
    $source = imagecreatefromstring(file_get_contents($sourceImage));
    $watermark = imagecreatefromstring(file_get_contents($watermarkImage));
   
    // Получаем размеры изображений
    $sourceWidth = imagesx($source);
    $sourceHeight = imagesy($source);
    $watermarkWidth = imagesx($watermark);
    $watermarkHeight = imagesy($watermark);
   
    // Размер блока для анализа (можно настроить)
    $blockSize = max($watermarkWidth, $watermarkHeight);
   
    $darkestX = 0;
    $darkestY = 0;
    $darkestValue = 255;
   
    // Проходим по изображению блоками
    for ($x = 0; $x <= $sourceWidth - $blockSize; $x += $blockSize) {
        for ($y = 0; $y <= $sourceHeight - $blockSize; $y += $blockSize) {
            $totalBrightness = 0;
            $pixelCount = 0;
           
            // Вычисляем среднюю яркость блока
            for ($px = $x; $px < min($x + $blockSize, $sourceWidth); $px++) {
                for ($py = $y; $py < min($y + $blockSize, $sourceHeight); $py++) {
                    $rgb = imagecolorat($source, $px, $py);
                    $r = ($rgb >> 16) & 0xFF;
                    $g = ($rgb >> 8) & 0xFF;
                    $b = $rgb & 0xFF;
                   
                    // Вычисляем яркость пикселя
                    $brightness = ($r + $g + $b) / 3;
                    $totalBrightness += $brightness;
                    $pixelCount++;
                }
            }
           
            $averageBrightness = $totalBrightness / $pixelCount;
           
            // Если это самый темный блок, сохраняем его координаты
            if ($averageBrightness < $darkestValue) {
                $darkestValue = $averageBrightness;
                $darkestX = $x;
                $darkestY = $y;
            }
        }
    }
   
    // Добавляем водяной знак в самую темную область
    imagecopy(
        $source,
        $watermark,
        $darkestX,
        $darkestY,
        0,
        0,
        $watermarkWidth,
        $watermarkHeight
    );
   
    // Сохраняем результат
    switch (strtolower(pathinfo($outputPath, PATHINFO_EXTENSION))) {
        case 'jpg':
        case 'jpeg':
            imagejpeg($source, $outputPath, 90);
            break;
        case 'png':
            imagepng($source, $outputPath);
            break;
        case 'gif':
            imagegif($source, $outputPath);
            break;
    }
   
    // Освобождаем память
    imagedestroy($source);
    imagedestroy($watermark);
}

// Пример использования:
$sourceImage = 'path/to/source.jpg';
$watermarkImage = 'path/to/watermark.png';
$outputPath = 'path/to/output.jpg';

addWatermark($sourceImage, $watermarkImage, $outputPath);
2025-02-11 12:00:47
http://php5.kiev.ua/manual/ru/image.examples-watermark.html

    Поддержать сайт на родительском проекте КГБ