As the necessity of graphics draw is invading the web development space. Watermark Images are being demanded most time in software development. Now PHP made it easy for people to be able to use the stack to create watermark Images by just writing PHP codes.
So, without wasting much of your time, let's jump straight into this tutorial.
PHP GD library has several amazing features that enable image manipulation. Images can be cropped, resized, rotated, watermarked, and more Using PHP GD.
In most web applications, you need to add dynamic images or add a watermark to images. In a previous tutorial, we explored How to Generate An Image: Using PHP GD Library. This guide will teach you how to use PHP to add watermarks to photos.
We can use the GD extension in PHP to add a watermark to images using the following steps:
Open the original image: $img = imagecreatefromjpeg("IMAGE.JPG");
Set the text color: $red = imagecolorallocatealpha($img, 255, 0, 0);
Add the text to the image: imagettftext($img, 18, 0, 0, 24, $red, "PATH\FONT.TTF", "COPYRIGHT");
imagejpeg($img, "WATERMARKED.JPG", 60);
There are several things you can use GD Library to build; in this tutorial, we will be building images that have watermarks! Below are examples of GD library watermarks.
With PHP GD, there are so many things that can be achieved with the library; that’s why GD is an outstanding side of PHP.
Examples of some use cases of GD library
Now, we will build a watermark that will be outputted as a file in our folder and browser.
First, you start a session and a redirect that will take us to another page where we will view the image. We can achieve that with the header location, and then we can visibly view the code.
<?php
session_start();
//here we are sending this our raw code to a new page
header("Location: other_file.php");
?>
Next, you create a variable that the image will be assigned to.
See the code below.
<?php
//hard code the image you want to watermark from the directory
$image1 = 'image/camera.jpg';
//hard code the watermark image from the directory
$image2 = 'image/potato.png';
?>
Then you will assign values to a list of variables in one operation.
<?php
//assign values to a list of variables in one operation
list($width, $height) = getimagesize($image2);
?>
Assign imagecreatefromstring()
the method to a variable inside the imagecreatefromstring()
. You will use another function to get the content of the image.
In our case, we will use the file_get_content()
to retrieve the image name, we assign it in a variable, and the file gets content that will contain a variable.
The Imagecreatefromstring()
the function provides an image identification that corresponds to the picture created using the provided data.
The code below is a typical example of what’s explained above.
<?php
$image1 = imagecreatefromstring(file_get_contents($image1));
$image2 = imagecreatefromstring(file_get_contents($image2));
?>
Now, let's copy and merge the parts of the image. What the function below does is that it takes the image variable and the watermark image variable and then merges them with other variables and values that were stated in the codes above.
After collecting all these values, the function will combine them to make it one so that we can be able to call one variable at the end of the day.
See the codes below.
<?php
//here we took a portion of a picture and combine it.
imagecopymerge($image1, $image2, 104, 160, 0, 0, $width, $height, 100);
?>
After going through the process of the imagecopymerge()
function, we can handle or do with one variable. Now we want the image shown as a png file. So it will be inserted in a function named imagepng()
.
The imagepng()
the method will convert the image to a png file.
Note: Inside the function will contain one image variable that has undergone the copy merge process.
<?php
//Create a PNG file and output it to a file or the browser.
imagepng($image1);
?>
So, let’s save the image in our folder (The folder where the coding is taking place). This time you will use the imagepng()
and it will accept two parameters. The first one is the variable that contains the image, and the second one is the name you want the image to bear in your folder.
Then we assign it to a variable $image1
, and call a $_SESSION['img']
then assign it to the variable containing the imagepng()
function.
<?php
//if you want to save the merged image
$image1 = imagepng($image1, 'merged.png');
$_SESSION['img'] = $image1;
?>
Here is the structure of the codes above.
<?php
session_start();
//here we are sending this our raw code to a new page
header("Location: other_file.php");
//hard code the image you want to watermark from the directory
$image1 = 'image/camera.jpg';
//hard code the watermark image from the directory
$image2 = 'image/potato.png';
//assign values to a list of variables in one operation
list($width, $height) = getimagesize($image2);
//returns an image identifier representing the image obtained from a given data
$image1 = imagecreatefromstring(file_get_contents($image1));
$image2 = imagecreatefromstring(file_get_contents($image2));
//here we took a portion of a picture and combine it.
imagecopymerge($image1, $image2, 104, 160, 0, 0, $width, $height, 100);
//Create a PNG file and output it to a file or the browser.
imagepng($image1);
//if you want to save the merged image
$image1 = imagepng($image1, 'merged.png');
$_SESSION['img'] = $image1;
?>
Then, the page where we are redirecting to is called other_file.php
and on that page, It will contain an image tag that will call the image from our file directory.
Just write the name of the generated image in the src=""
above the page, you will create a session in a <?php ?>
tag.
See the code below.
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Final</title>
</head>
<body>
<img src="merged.png">
</body>
</html>
Now, look at where your saved image file is.
Save the page go to the browser, and refresh the page. Below is the output from the browser. The output will also be generated in the file directory.
This is how you add a watermark to an image. With this strategy, you can grow your Tech skill in the sense that the images in your work will be difficult to be stolen cause it has a watermark on them.
So the concept behind Watermark is that it’s one of the most excellent methods for preventing picture theft or re-use by another person.
By using a watermark, you can make the owner of the photo visible. The watermark makes it easier to determine who took the photo or image. In copyrighted images, the watermark stamp is typically utilized.
Images typically include a watermark that includes the creator's name or the corporate logo. Now to create a watermark image, we will use a very dynamic concept. First, we will have an index page.
The page where you put in your watermark image and the image you want to watermark. The index.php will look very simple with the code below.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>GD</title>
</head>
<body>
<div>
<form class="form" action="watermark_action.php" method="post" enctype="multipart/form-data">
<p>Select An Image File to Upload:</p>
<input class="files" type="file" name="i_file">
<p>Select Your Choice of watermark Image File to Upload:</p>
<input class="files" type="file" name="w_file">
<input type="submit" class="btn" name="submit" value="Upload">
</form>
</div>
</body>
</html>
Here is the CSS of the Above code. Create a style.css file and write the following code inside of it.
*{
padding: 0;
margin: 0;
box-sizing: border-box;
text-align: center;
}
div.form{
display: block;
}
form{
margin-top: 40px;
display: inline-block;
margin-right: auto;
margin-left: auto;
padding: 30px;
background-color: ;
box-shadow: 5px 5px 10px 10px lightgray;
}
p{
font-size: 18px;
color: black;
}
input{
padding: 10px;
margin: 5px;
}
.files{
padding: 10px;
margin: 5px;
}
.btn{
padding: 10px;
width: 100%;
border: 0;
border-radius: 20px;
}
.btns{
padding: 10px;
width: 20%;
margin: 5px;
background-color: red;
border: 0;
color: white;
text-decoration: none;
border-radius: 20px;
position: absolute;
right: 0;
bottom: 0;
}
.btn:hover{
background-color: black;
color: white;
transform: scale(0.9);
transition: 2s;
}
After this process, you’ll then have a Styled form like this:
Now with the codes above, you will be able to fill in your choice of image and your choice watermark.
Next, you will create another file and give it the name of your action attribute of the form we just created. Create a file and give it the name of your action attribute. In our case watermark_action.php
.
So, you will open the file and paste the code below. I’ll briefly explain what I did in the code.
Firstly you need to create a folder named image. You can name it anything you wish. This image folder will contain the image you want to watermark; you’ll save it in the folder first before calling it in another file.
Then on the Action page, you’ll create a session so we can be able to store information(in variables) to be used across multiple pages.
Now you will create a variable that will check if your code has an error.
Below is the code that enables you to do some error handling.
<?php
//declare an error variable and an error_msg variable
//the variables enable you to assign your errors to the variable.
$error = 0;
$error_msg = "";
?>
As we proceed, you will see the use of the error variable.
The next thing to do is to create a function. The reason for this function is to make it possible to call the conditional statements written inside of the function at once instead of calling everything the switch case one after the other.
The function below accepts two parameters. The first parameter is to convert the string of the image name to lowercase using the strtolower()
method and saved it back in the $ext variable.
The code below explains more about it.
<?php
//create a function that accepts two parameters
function make_image($ext, $src){
$ext = strtolower($ext);
//Load the stamp and the photo to apply the watermark to
switch ($ext) {
case 'jpg':
return $result = imagecreatefromjpeg($src);
break;
case 'jpeg':
return $result = imagecreatefromjpeg($src);
break;
case 'png':
return $result = imagecreatefrompng($src);
default:
return $result = imagecreatefromjpeg($src);
break;
}
?>
Note that the default of the switch case is necessary; if all the conditions in the case didn’t run, the default will run.
The next step is to create a folder where the images that are being selected will be in. It will be visible on your code editor once created. You can name it whatever you want, but I named mine images
and assigned them to a variable.
Save the name of the two input tags in the global variable $_FILES
and insert it in a variable so that it can be easily called.
We used an if statement to check if the image or the watermark image is empty.
The code below explains it more.
<?php
//you will write the name of the image folder and assign it to a variable
$targetDir = "images/";
//save the name of the files in a variable image, watermark
$image = $_FILES['i_file'];
$watermark = $_FILES['w_file'];
//checks if the image and watermark are empty
if ($image['error'] != 0 || $watermark['error'] !=0) {
$error = 1;
$error_msg.="error uploading image <br>";
}
?>
You have been able to check if the image is empty. If it’s empty, it will throw an error that says Error uploading image.
Now we will change the name of our images to a random number when submitted. all you need to do is to call the variable and save the target directory, also known as targetDir
inside a new variable.
The pathinfo()
method will get the name of the file and get only the last extension if the path has more than one extension.
Take your time and study the code below; you will have a better understanding of what was previously explained.
<?php
$realimage = $image['tmp_name'];
$realwatermark = $watermark['tmp_name'];
// File upload path
$imagepath = $targetDir . sha1(microtime()) . $image['name'];
$watermarkpath = $targetDir . sha1(microtime()) . $watermark['name'];
//if the route contains more than one extension, it just returns the most recent extension.
$image_ext = pathinfo($image['name'],PATHINFO_EXTENSION);
$watermark_ext = pathinfo($watermark['name'], PATHINFO_EXTENSION);
?>
We have been able to work on the path of both the watermark image and the main image.
Now, having worked on the directory of the image, we need to list what type of image extension is allowed in our project, including the font size of the extensions.
So below, we will list the type of extensions we need and perform some if statements. The first if statement contains an in-built function in_array()
.
What the in_array()
does is that it ****looks up a particular value within an array. So they in_array()
will check if the listed file type is valid or not.
And the second if statements, when the conditions are met, you will move the uploaded file to its path.
<?php
//an array of image extensions saved in a variable $allowedType
$allowedType = array('jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG');
//Get the array extension and the type that is allowed
if (in_array($image_ext, $allowedType)) {
if (in_array($watermark_ext, $allowedType)) {
//move the file you want to upload, to their various paths or destination
move_uploaded_file($realwatermark, $watermarkpath);
move_uploaded_file($realimage, $imagepath);
//calling the above function and saving it inside their various variable
$p_image = make_image($image_ext, $imagepath);
$p_watermark = make_image($watermark_ext, $watermarkpath);
}else{
//if the watermark type is not in the array, it will throw 1 error
$error = 1;
$error_msg.="Invalid watermark Type";
}
}else{
//if the watermark type is not in the array, it will throw 1 error
$error = 1;
$error_msg.="Invalid image Type";
}
?>
We are almost rounding up,
The type of image set has undergone several conditions.
Just read the comments on the code below. You’ll get a clearer understanding of each line of code. Below we set the marge bottom or marge right of the watermarked image.
And we also get the height and weight of the watermark. worked on the positioning and saved the image in our image folder and the $_SESSION
variable.
Immediately we do a redirect with our header()
location, and it will take us to another interface named watermark.php.
Here is the code that performs what was previously stated.
<?php
//Set the margins for the watermark
$marge_right = 10;
$marge_bottom = 10;
//Get the height/width of the watermark image
$sx = imagesx($p_watermark);
$sy = imagesy($p_watermark);
// Copy the watermark image onto our photo using the margin offsets and
// the photo width to calculate the positioning of the watermark.
imagecopy($p_image, $p_watermark, imagesx($p_image) - $sx - $marge_right, imagesy($p_image) - $sy - $marge_bottom, 0, 0, imagesx($p_watermark), imagesy($p_watermark));
//Save the image
imagepng($p_image, $imagepath);
imagedestroy($p_image);
//Save the $imagepath in the SESSION variable
$_SESSION['img'] = $imagepath;
//will take you to the page where you will see the image you watermarked.
header("Location: watermark.php");
?>
We’re done with the explanation of the above code.
Here’s everything explained above. You can look at it meticulously to see if there’s anything that isn’t right.
<?php
// Path configuration Page
session_start();
//declare an error variable and an error_msg variable
//the variables enable you to assign your errors to the variable.
$error = 0;
$error_msg = "";
//create a function that accepts two parameters
function make_image($ext, $src){
//Load the stamp and the photo to apply the watermark to
$ext = strtolower($ext);
switch ($ext) {
case 'jpg':
return $result = imagecreatefromjpeg($src);
break;
case 'jpeg':
return $result = imagecreatefromjpeg($src);
break;
case 'png':
return $result = imagecreatefrompng($src);
default:
return $result = imagecreatefromjpeg($src);
break;
}
}
//you will write the name of the image folder and assign it to a variable
$targetDir = "image/";
//save the name of the files in a variable image, watermark
$image = $_FILES['i_file'];
$watermark = $_FILES['w_file'];
//checks if the image and watermark are empty
if ($image['error'] != 0 || $watermark['error'] !=0) {
$error = 1;
$error_msg.="error uploading image <br>";
}
$realimage = $image['tmp_name'];
$realwatermark = $watermark['tmp_name'];
// File upload path
$imagepath = $targetDir . sha1(microtime()) . $image['name'];
$watermarkpath = $targetDir . sha1(microtime()) . $watermark['name'];
$image_ext = pathinfo($image['name'],PATHINFO_EXTENSION);
$watermark_ext = pathinfo($watermark['name'], PATHINFO_EXTENSION);
//an array of image extensions saved in a variable $allowedType
$allowedType = array('jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG');
if (in_array($image_ext, $allowedType)) {
//Get the array extension and the type that is allowed
if (in_array($watermark_ext, $allowedType)) {
//move the file you want to upload, to their various paths or destination
move_uploaded_file($realwatermark, $watermarkpath);
move_uploaded_file($realimage, $imagepath);
//calling the above function and saving it inside their various variable
$p_image = make_image($image_ext, $imagepath);
$p_watermark = make_image($watermark_ext, $watermarkpath);
}else{
//if the watermark type is not in the array, it will throw 1 error
$error = 1;
$error_msg.="Invalid watermark Type";
}
}else{
//if the watermark type is not in the array, it will throw 1 error
$error = 1;
$error_msg.="Invalid image Type";
}
//Set the margins for the watermark
$marge_right = 10;
$marge_bottom = 10;
//Get the height/width of the watermark image
$sx = imagesx($p_watermark);
$sy = imagesy($p_watermark);
//Copy the watermark image onto our photo using the margin offsets and
//the photo width to calculate the positioning of the watermark.
imagecopy($p_image, $p_watermark, imagesx($p_image) - $sx - $marge_right, imagesy($p_image) - $sy - $marge_bottom, 0, 0, imagesx($p_watermark), imagesy($p_watermark));
//Save the image
imagepng($p_image, $imagepath);
imagedestroy($p_image);
//Save the $imagepath in the SESSION variable
$_SESSION['img'] = $imagepath;
//will take you to the page where you will see the image you watermarked
header("Location: watermark.php");
?>
After all these, we need to output it in another named watermark.php.
On this page, you will write a few PHP lines of code. First, you will start a session because all we did on the action page was saved in a session, so while opting for it, you need to start a session. After starting the session, then you will call the variable that the image was saved within the action page.
Then the final thing to do is to create an image tag in the src
of the <img
src="">
tag you will use the short PHP tag to echo the variable that has the session assigned to it. By writing that code, you can now visibly see your output.
<?php
session_start();
$imagepath = $_SESSION['img'];
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="content-type" name="viewport" content="width=device-width, text/html initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<!-- <meta content="; charset=UTF-8"> -->
<title>GD</title>
</head>
<body>
<h1>Your Result</h1>
<img src="<?=$imagepath ?>">
<a href="index.php" class="btns">Go back to for more Watermarking</a>
</body>
</html>
We’ve come to the end of this tutorial. Hopefully, you gain a ton of value from this it.
Learning how to create a watermark Image and text, Using PHP GD Library.
This is not the end of the tutorial. We’ll talk more about what you can use GD Library to do.
Till next time, enjoy!
Emmanuel Okolie kick-started his journey as a software engineer in 2020. Over the years, he has grown full-blown skills in JavaScript, PHP, HTML & CSS, and more.
He is currently freelancing, building websites for clients, and writing technical tutorials, teaching others how to do what he does.
Emmanuel Okolie is open and available to hear from you. You can reach him on Linked In, Facebook, Github, Twitter, or on his website.
Also published here.