November 14, 2019
Upload and Add Watermark to Image using PHP

Upload and Add Watermark to Image using PHP

When you look up photos online, you will notice that some of them are watermarked. A watermark is usually some text or a logo overlaid on the photo that identifies who took the photo or who owns the rights to the photo. Some professionals recommend adding watermarks to your photos before sharing them on social media to prevent other people from using your photos as their own and profiting off your work.

PHP GD library provides an easy way to add a watermark image to photo using alpha channels. The dynamic watermark feature is very useful for the images to upload management section. In this tutorial, we will show you how to upload image to server and add watermark to image using PHP.

Prerequisites

Here is some setups required for this tutorial:

  • PHP 5+
  • PHP GD extension

File Upload Form

A HTML form allow uploading an image

The tag will contains the following attributes:

  • method="post"
  • enctype=”multipart/form-data”

Also, make sure tag contains type="file" attribute.

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select Image File to Upload:
    <input type="file" name="file">
    <input type="submit" name="submit" value="Upload">
</form>

Upload Image and Add Watermark with PHP (upload.php)

The upload.php file handles the image upload and watermark adding functionality.

<?php 
// Path configuration 
$targetDir = "uploads/"; 
$watermarkImagePath = 'path/to/your-logo.png'; 
 
$statusMsg = ''; 
if(isset($_POST["submit"])){ 
    if(!empty($_FILES["file"]["name"])){ 
        // File upload path 
        $fileName = basename($_FILES["file"]["name"]); 
        $targetFilePath = $targetDir . $fileName; 
        $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION); 
         
        // Allow certain file formats 
        $allowTypes = array('jpg','png','jpeg'); 
        if(in_array($fileType, $allowTypes)){ 
            // Upload file to the server 
            if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){ 
                // Load the stamp and the photo to apply the watermark to 
                $watermarkImg = imagecreatefrompng($watermarkImagePath); 
                switch($fileType){ 
                    case 'jpg': 
                        $im = imagecreatefromjpeg($targetFilePath); 
                        break; 
                    case 'jpeg': 
                        $im = imagecreatefromjpeg($targetFilePath); 
                        break; 
                    case 'png': 
                        $im = imagecreatefrompng($targetFilePath); 
                        break; 
                    default: 
                        $im = imagecreatefromjpeg($targetFilePath); 
                } 
                 
                // Set the margins for the watermark 
                $marge_right = 10; 
                $marge_bottom = 10; 
                 
                // Get the height/width of the watermark image 
                $sx = imagesx($watermarkImg); 
                $sy = imagesy($watermarkImg); 
                 
                // Copy the watermark image onto our photo using the margin offsets and  
                // the photo width to calculate the positioning of the watermark. 
                imagecopy($im, $watermarkImg, imagesx($im) - $sx - $marge_right, imagesy($im) - $sy - $marge_bottom, 0, 0, imagesx($watermarkImg), imagesy($watermarkImg)); 
                 
                // Save image and free memory 
                imagepng($im, $targetFilePath); 
                imagedestroy($im); 
     
                if(file_exists($targetFilePath)){ 
                    $statusMsg = "The image with watermark has been uploaded successfully."; 
                }else{ 
                    $statusMsg = "Image upload failed, please try again."; 
                }  
            }else{ 
                $statusMsg = "Sorry, there was an error uploading your file."; 
            } 
        }else{ 
            $statusMsg = 'Sorry, only JPG, JPEG, and PNG files are allowed to upload.'; 
        } 
    }else{ 
        $statusMsg = 'Please select a file to upload.'; 
    } 
} 
 
// Display status message 
echo $statusMsg;

Here is how the sea of texts above work:

  • Use PHP pathinfo() function to get the file extension and check whether the selected file type is within the allowed file format.
  • Upload file to server using move_uploaded_file() function in PHP.
  • Only JPG, JPEG & PNG Are allowed
  • Load and create a new stamp from the watermark image using imagecreatefrompng() function.
  • Load and create a new image from the uploaded image based on the file type.
  • Set the right and bottom margin for the watermark image.
  • Get the height and width of the watermark image.
  • Copy the watermark image as configured in $watermarkImagePath onto the uploaded photo using imagecopy() function.
  • Use margin offsets and image width to calculate the positioning of the watermark.
  • Save image with watermark using imagepng() function. The image is saved in the directory configured in $targetDir.
  • Free memory associated with image resource using imagedestroy() function.
  • Display the watermarked image upload status.

Note:

Change $watermarkImagePath to your watermark image path

Join the discussion

Danny2507 Blog