Add Watermark to Images using PHP

Date Posted: January 21, 2015, 5:14 am


watermark_images_using_php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<?php
/**
 * Adds a watermark / stamp to images.
 *
 * @author      Carl Victor Fontanos
 * @authoruri   www.carlofontanos.com
 * @date        01-20-2015
 *
 */

function cvf_add_watermark($image_path, $stamp_path){
   
    $file = pathinfo($image_path);
   
    // Declare valid formats
    $valid_formats = array("jpg", "jpeg", "gif", "png");
   
    // Check if image exists
    if(!file_exists($image_path)){
        return false;
   
    // Check if file meets extension requirements
    } else if(!in_array($file['extension'], $valid_formats)) {
        return false;
       
    } else {
       
        // Load the stamp and the photo to apply the watermark to
        $stamp = imagecreatefrompng($stamp_path);
       
        // Designate image depending on extension
        if($file['extension'] == 'jpg' || $file['extension'] == 'jpeg'){
            $image = imagecreatefromjpeg($image_path);
        } else if ($file['extension'] == 'png'){
            $image = imagecreatefrompng($image_path);
        } else if ($file['extension'] == 'gif'){
            $image = imagecreatefromgif($image_path);
        }
   

        // 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(
            $image,
            $stamp,
            imagesx($image) - $sx - $marge_right,
            imagesy($image) - $sy - $marge_bottom,
            0,
            0,
            imagesx($stamp),
            imagesy($stamp)
        );

        // Output as PNG file and free memory
        header('Content-type: image/png');
        imagepng($image);
        imagedestroy($image);
    }
}

?>

Usage

1
echo cvf_add_watermark('http://carlofontanos.com/path/to/image/example.png', 'watermark.png');

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me