In this article, we’ll show you how to Upload and Add a Watermark to an Image using PHP. WaterMark is very useful to protect original images and documents are pdf, word, excel ….etc. it takes only Two steps are HTML file and PHP File, Image Upload using HTML file and add watermark to an image using PHP File

watermark adding Image upload in PHP is very easy. It can be use image or text as a watermark onto a target document/layer. mostly, if you are using watermark image or text is used in the copyrighted images.In this tutorial, we will show you how to PHP image upload to server and add watermark to image or text.

Create Database and Tables

In the following example, we will start How To Add Watermark To Image Using PHP. So first, create a MySQL database called codeat21. And after that, create the table name called posts.

Database information

  • Database Name – codeat21
  • Table Name – posts
CREATE TABLE `posts` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
 

Database Configuration

First, Create a dbConfig.php file to connect the MySQL database are hostname, username, Password, and database name.

dbConfig.php
<?php //DB details $dbHost = 'localhost'; $dbUsername = 'root'; $dbPassword = ''; $dbName = 'codeat21'; //Create connection and select DB $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); if ($db->connect_error) { die("Unable to connect database: " . $db->connect_error); } ?>

So let’s start the coding. Project structure your folder as follows.

  • index.php
  • upload.php
  • dbConfig.php

Create Image Upload Form (index.php) and Below Code

index.php
<?php include_once 'upload.php'; ?> <!DOCTYPE html> <html lang="en-US"> <head> <title>Upload Image with Watermark using PHP by Codeat21</title> <meta charset="utf-8"> <!-- Stylesheet file --> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <h1>Upload and Add Watermark to Image using PHP</h1> <!-- Display status message --> <div class="status"> <?php echo !empty($statusMsg)?$statusMsg:''; ?> </div> <div class="form-group"> <!-- Image upload form --> <form action="" method="post" enctype="multipart/form-data" class="form-inline"> <div class="groups"> <label for="file">Select Image File to Upload:</label> <input type="file" name="file" class="form-control"> <input type="submit" name="submit" value="Upload" class="btn btn-success"> </div> </form> <?php if(!empty($uploadedFileName)){ ?> <h5>Watermarked Image</h5> <div class="gallery"> <img src="<?php echo 'uploads/'.$uploadedFileName; ?>" alt=""> </div> <?php } ?> </div> </div> </body> </html>

Let’s create an upload HTML form tag contains the following attributes are method and enctype, The enctype is Send form-data encoded as “multipart/form-data”

Note: The from enctype attribute can be used only if method=”post”.

PHP Image Upload and Add Watermark

In upload.php, The imagecopy() function is using one image onto another image layer as a watermark is called the imagecopy() function.

PHP move_uploaded_file function is using image file upload to server.

PHP imagepng() function is using Save image with watermark.

Create a new image uploaded based on the file type.

If you are clear on the full complete PHP code below, we call the PHP imagecopy() function.

upload.php
<?php // Path configuration include_once 'dbConfig.php'; $targetDir = "uploads/"; $watermarkImagePath = 'codeat21-logo.png'; $uploadedFileName = $statusMsg = ''; if(isset($_POST["submit"])){ if(!empty($_FILES["file"]["name"])){ // File upload path $fileName = time().'_'.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); $uploadedFileName = $fileName; if(file_exists($targetFilePath)){ $add = mysqli_query($db,"insert into posts (image) values('$targetFilePath')"); if($add){ $statusMsg = '<p style="color: #07c707;">The image with watermark has been uploaded successfully.</p>'; }else{ $statusMsg = '<p style="color: #EA4335;"> Server Problem, please try again.</p>'; } }else{ $statusMsg = '<p style="color: #EA4335;">Image upload failed, please try again.</p>'; } }else{ $statusMsg = '<p style="color: #EA4335;">Sorry, there was an error uploading your file.</p>'; } }else{ $statusMsg = '<p style="color: #EA4335;">Sorry, only JPG, JPEG, and PNG files are allowed to upload.</p>'; } }else{ $statusMsg = '<p style="color: #EA4335;">Please select a file to upload.</p>'; } } // Display status message //echo $statusMsg; ?>

Conclusion

In this post, you will learned how to Upload and Add a Watermark to an Image using PHP Tutorial is over. You can customize this code further as per your requirement. The supporting Github repository is available for this post source code. Also, check it out on youtube for a demo.

Download source code from github   |   Live Demo – youtube