Wednesday, 19 February 2020

How to Add Watermark in Image using PHP



In the web world, Watermark is the one way to protect our image from being theft or re-used by another user. So, if you want create your ownership on image, for this you have to add watermark on an image. There are some another benefits of put watermark on your image is that it will identify that particular image or photo is created or uploaded by you. In most of the website, logo is used as watermark and put on image. For this all feature here in this post, we will show you how to add watermark to image using PHP.

Now in your mind how can we add watermark to a image in PHP. So, we can implement put watermark on image while uploading of Image using PHP. PHP has GD library which has provides us simple way to add a watermark image to any photo by using alpha channels. Here we will make add dynamic watermark on image feature will helps you to manage image management section. In this tutorial, we will first upload image on server and add watermark to image using PHP.

For make Add watermark on Image using PHP script, here we will write PHP script, that will process two images, one will be the image which we will upload through form, and second will be logo or business stamp which we will be use as watermark image. In PHP script first it will upload select image file to server and then after by using PHP GD library function watermark image will be put on uploaded image. Generally, we have to use transparent image has been used as watermark image, so it has easily placed on uploaded image. So, this post main target is that to learn How to add a watermark to Image using PHP. Below you can find source code of this tutorial.







Source Code


index.php



<?php

//index.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$message = '';

if(isset($_POST["upload"]))
{
  if(!empty($_FILES["select_image"]["name"]))
  { 
    $extension = pathinfo($_FILES["select_image"]["name"],PATHINFO_EXTENSION);
    
    $allow_extension = array('jpg','png','jpeg');

    $file_name = uniqid() . '.' . $extension;

    $upload_location = 'upload/' . $file_name;

    if(in_array($extension, $allow_extension))
    {
      $image_size = $_FILES["select_image"]["size"];
      if($image_size < 2 * 1024 * 1024)
      {
        if(move_uploaded_file($_FILES["select_image"]["tmp_name"], $upload_location))
        { 
          
          $watermark_image = imagecreatefrompng('round-logo.png');
          if($extension == 'jpg' || $extension == 'jpeg')
          {
            $image = imagecreatefromjpeg($upload_location);
          }

          if($extension == 'png')
          {
            $image = imagecreatefrompng($upload_location);
          }

          $margin_right = 10; 
          $margin_bottom = 10;

          $watermark_image_width = imagesx($watermark_image); 
          $watermark_image_height = imagesy($watermark_image);  

          imagecopy($image, $watermark_image, imagesx($image) - $watermark_image_width - $margin_right, imagesy($image) - $watermark_image_height - $margin_bottom, 0, 0, $watermark_image_width, $watermark_image_height); 

          imagepng($image, $upload_location); 

          imagedestroy($image);
          if(file_exists($upload_location))
          { 
            $message = "Image Uploaded with Watermark";
            $data = array(
              ':image_name'   =>  $file_name
            );
            $query = "
            INSERT INTO images_table 
            (image_name, upload_datetime) 
            VALUES (:image_name, now())
            ";
            $statement = $connect->prepare($query);
            $statement->execute($data);
          }
          else
          { 
            $message = "There is some error, try again";
          }
        }
        else
        {
          $message = "There is some error, try again";
        }
      }
      else
      {
        $message = "Selected Image Size is very big";
      }      
    }
    else
    {
      $message = 'Only .jpg, .png and .jpeg image file allowed to upload';
    }
  }
  else
  { 
    $message = 'Please select Image';
  } 
}

$query = "
SELECT * FROM images_table 
ORDER BY image_id DESC
";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();



?>

<!DOCTYPE html>
<html>
  <head>
    <title>How to Dynamically Add Watermark to Image using PHP</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  </head>
  <body>
    <br />
    <div class="container">
      <h3 align="center">How to Dynamically Add Watermark to Image using PHP</h3>
      <br />
      <?php
      if($message != '')
      {
        echo '
        <div class="alert alert-info">
        '.$message.'
        </div>
        ';
      }
      ?>
      <div class="panel panel-default">
        <div class="panel-heading">Add Wartermark to an Image</div>
        <div class="panel-body">
          <form method="post" enctype="multipart/form-data">
            <div class="row">
              <div class="form-group">
                <label class="col-md-6" align="right">Select Image</label>
                <div class="col-md-6">
                  <input type="file" name="select_image" />
                </div>
              </div>              
            </div>
            <br />
            <div class="form-group" align="center">
              <input type="submit" name="upload" class="btn btn-primary" value="Upload" />
            </div>
          </form>
        </div>
      </div>
      <div class="panel panel-default">
        <div class="panel-heading">Uploaded Image with Watermark</div>
        <div class="panel-body" style="height: 700px;overflow-y: auto;">
          <div class="row">
          <?php
          foreach($result as $row)
          {
            echo '
            <div class="col-md-2" style="margin-bottom:16px;">
              <img src="upload/'.$row["image_name"].'" class="img-responsive img-thumbnail"  />
            </div>
            ';
          }
          ?>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>





Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `images_table`
--

CREATE TABLE `images_table` (
  `image_id` int(11) NOT NULL,
  `image_name` varchar(250) NOT NULL,
  `upload_datetime` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `images_table`
--
ALTER TABLE `images_table`
  ADD PRIMARY KEY (`image_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `images_table`
--
ALTER TABLE `images_table`
  MODIFY `image_id` int(11) NOT NULL AUTO_INCREMENT;


With the help of above source code, you can make one functionality like you can upload an image with watermark and save one server by using PHP. When you have upload image then it will automatically add watermark on image using PHP. You can also change the position of watermark image by change the value of margin offset, you can add watermark on an image at any position. By using this tutorial, you can also add text as watermark to image using PHP





5 comments:

  1. Hello, this is seriously useful tutorial but ı have some problems about it. ı'm trying to upload an image with watermark to my webpage via your codes and it is working for small photos but ı'm designing a photography webpage and some of photos which ı want to upload are big. How can ı solve this problem?

    Thank you for your helps...

    ReplyDelete