Windows.  Viruses.  Laptops.  Internet.  Office.  Utilities.  Drivers

If you want to add a watermark to a photo without bothering with image editors or add it while uploading photos to the server, then this tutorial is for you.

In this tutorial, I'll show you how to add a watermark to an image on the fly without actually changing the original image. First of all, you will need an image to use as your watermark.

Then we form the file header:

// this line will tell the browser that we are passing a jpg image header("content-type: image/jpeg");

Then we form png image and get its dimensions:

// create a watermark in png format $watermark = imagecreatefrompng("watermark.png"); // get the width and height $watermark_width = imagesx($watermark); $watermark_height = imagesy($watermark);

We will do the same with the original image, but only in jpg format. This is common for photos that are uploaded through a form. We proceed as follows:

// jpg creation images $image_path = "original.jpg"; $image = imagecreatefromjpeg($image_path); // get the image size $size = getimagesize($image_path);

Now we need to place a watermark on the image:

// place a watermark at the bottom right. Indent 5px $dest_x = $size - $watermark_width - 5; $dest_y = $size - $watermark_height - 5;

Next, let's set up the blending options for both images:

Imagealphablending($image, true); imagealphablending($watermark, true);

Finally we create a new image using the parameters:

// create a new image imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height); imagejpeg($image);

It is important to clean up after yourself:

// free up memory imagedestroy($image); imagedestroy($watermark);

You can use Photoshop to adjust the transparency of the watermark.

That's all with theory. Now let's apply our knowledge to a real project. All this must be saved to a file. For example, called watermark.php

Header("content-type: image/jpeg"); // get the image name via GET $image = $_GET["image"]; // create a watermark $watermark = imagecreatefrompng("watermark.png"); // get the height and width of the watermark $watermark_width = imagesx($watermark); $watermark_height = imagesy($watermark); // create a jpg from the original image $image_path = "/path/to/image/folder/" . $image; $image = imagecreatefromjpeg($image_path); //if something goes wrong if ($image === false) ( return false; ) $size = getimagesize($image_path); // place a watermark on the image $dest_x = $size - $watermark_width - 5; $dest_y = $size - $watermark_height - 5; imagealphablending($image, true); imagealphablending($watermark, true); // create a new image imagecopy($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height); imagejpeg($image); // free up memory imagedestroy($image); imagedestroy($watermark);

Now, in order to show a photo with a watermark without changing the original image, use the following code.

Owners of websites (forums, message boards, etc.) are often faced with the problem of creating watermarks on all large images of the site.

Of course, you can solve this problem by manually creating a watermark on each image, however, firstly, this takes a lot of time, and secondly, it becomes necessary to store two versions of the image, with and without a watermark.

A solution to this problem can be to dynamically apply a watermark to the image before transmitting it to the site visitor.

There is a solution to this problem on the Internet in the form of two files, the contents of which are given below.
Source code of the ".htaccess" file

DirectoryIndex index.php RewriteEngine On RewriteCond %(REQUEST_FILENAME) -f RewriteRule ^(.*)$ /watermark/_watermark.php

Source code of the file "_watermark.php"

250) && ($info_o > 250)) ( // For images without an alpha channel // The last parameter of the function is the degree of opacity of the watermark imageCopyMerge($out, $watermark, ($info_o-$info_w)/2, ($info_o -$info_w)/2, 0, 0, $info_w, $info_w, 25); // For images with an alpha channel // In this case, the transparency is adjusted by the alpha channel of the image itself // imageCopy($out, $watermark, ($info_o-$info_w)/2, ($info_o-$info_w)/2, 0, 0, $info_w, $info_w); ) switch ($info_o) ( case 1: imageGIF($out); break; case 2: imageJPEG($out); break; case 3: imagePNG($out); break; default: return false; ) imageDestroy($out); imageDestroy($original); imageDestroy($watermark); return true; ) ?>

The solution boils down to the following: the “.htaccess” file is placed in the directory with the image files. In addition to it, a “watermark” folder is created on the server, in which there is a script file “_watermark.php” and the actual watermark file “watermark.png”.

At the same time, compared to the original version found on the Internet, I made minor changes to both text files.

In the ".htaccess" file, in regular expression The "jpeg" extension has been added to search for image files, as it is also frequently encountered.

The "_watermark.php" script has been reworked in such a way as to place the watermark in the center of the image (this was required by the specifics of the problem being solved) and the ability to adjust the transparency of the created watermark has been added (the comments in the body of the script will help you configure this parameter yourself).

You should also pay attention to the fact that placing the "watermark" folder in the folder with images, as the original sources advise, we will not achieve the desired result, because in this case we will have to have its own ".htaccess" file and "watermark" folder in each folder. This is due to the fact that the ".htaccess" file specifies absolute paths from the site's root directory to the "_watermark.php" file. Thus, having a separate “watermark” subfolder in each folder with images, if we need to change the watermark (or the script that overlays it on the image), we will have to make changes in all folders.

To avoid this problem, I recommend creating a "watermark" folder in the root directory of the site, and placing a ".htaccess" file in the image directories without having to change it every time. In this case, to change the watermark or script, we will need to make changes in only one place on the site. Create different watermarks for different folders with images in this case you can refer from different files".htaccess" to different scripts, for example "_watermark-1.php", "_watermark-2.php", etc.

Thus, to summarize, we can say that to apply watermarks to all images of the site, you need to download the archive attached below, unpack it, place the “watermark” folder in the root directory of the site, replace the watermark file “watermark.png” in it with your own own, and place the ".htaccess" file in those site directories, images from which should be watermarked.

You can download the archive containing all the necessary files at this

In some cases, adding watermarks to images you post on your site is the only way at least somehow protect them from theft. In addition, they say that such watermarks attract additional traffic.

There are many ways to watermark an image with using PHP, but my customer needed an application method that would allow him to change the watermark to a new one at any time.

As it turns out, there is such a solution.

This is usually used by people who develop websites with mostly graphic content.

Selecting a watermark method

The problem with implementing all this mess is choosing how to apply the watermark between performance and flexibility. Ideal solution, which would suit everyone simply does not exist. This is why there are many implementations.

In my case, the customer reserves the right to rebrand at any time and instead "Horns and hooves" write “Hooves and Horns”. The watermarking method you choose should tolerate this too.

The essence of the watermarking technology described here is to add this very mark every time an image is loaded. Yes, this method carries a number of limitations that can significantly affect performance, but as they say, the customer is always right and therefore if those. the task requires dynamically applying a watermark, then this is exactly what needs to be done.

If anyone has an easier way, then you are welcome to comment. It will be interesting to listen.

Before presenting some code, I would like to describe the advantages, as well as give a working example.

Pros:

  • you can change the watermark at least 500 times a day;
  • can be deployed in any CMS (it is not tied to it in any way).

Minuses:

  • depends on the performance of the hosting (if you have a lot of images or they are of high resolution, this can put a significant load on the server);
  • an inquisitive mind will still be able to remove your watermark.

Conclusions: for posting a small number of images with watermarks, this method is perfect, but if you are going to open a photo gallery, then it would be better to look for something less heavily loaded.

Example

Implementing a watermark using PHP

As promised, you don’t need to have any special knowledge for this, you need to:

  1. file, which is in the archive, and place it in the root directory of your site;
  2. We place the image that will act as a watermark in the root directory of the site and name it (in my case it’s a white brush stroke, so the link may not be visible against the background of your browser). The image must be a PNG, since it has a transparent layer. If you want to use GIF, you need to edit the file image.php;
  3. in the place where you want to display the image with the watermark, place the code:

That's all. Everyone is happy, both you and the customer.

You take a big risk when you publish your images and videos on the Internet, since your materials can easily be copied to hundreds of other resources. It wouldn’t be very cool to find your picture for a news story, for example, which you worked hard on, on another site without indicating the source, that is, your site, would it? To put it mildly, you will be upset, but if it was not simple picture to the news, and complex work in Photoshop, to say that you will be angry is to say nothing! So what can you do to protect your graphics?

To protect the copyright of images or videos on the Internet, a digital watermark or digital watermark is usually used for convenience. Attach a digital signature to each uploaded image in order to protect it. The CEZ can be the logo of your website or company, beautifully and aesthetically placed on uploaded images.

Let's first create a file containing the necessary settings in the form of constants - /config.php:

Define("WATERMARK_OVERLAY_IMAGE", "/develop/images/watermark.png"); // Path to your Central Exhibition Hall define("WATERMARK_OUTPUT_QUALITY", 100); // Quality of the resulting image from digital video recording. Remember that quality directly affects file size. define("UPLOADED_IMAGE_DESTINATION", "/develop/folder1/"); // Path to the location of the original loaded images define("WATERMARK_IMAGE_DESTINATION", "/develop/folder2/"); // Path to images with overlaid digital waveform

Let's collect the files created above in the file executing the download /upload.php

Include("config.php"); include("functions.php"); $result = ImageUpload($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"]); if ($result === false)( echo "Download failed!"; )

For example, if the image being loaded was:

Then after downloading and applying a watermark, you will get the following image:

IN in this example the downloaded image is saved in one folder, and the image on which a digital watermark has been superimposed in another, so that you always have access to the original images, but, of course, it is worth posting images from the digital exhibition center on the site.

(178.4 KiB, 989 hits)

One of the interesting things you can do with the PHP GD graphics library is a class that puts watermarks on an image. In a nutshell, watermarking is a technology for protecting digital images from unauthorized use by adding watermarks or signatures to them. As a consequence of this, it can be (and generally is) used to determine the owner of the copyright in an image. So, let's move on.

Introduction

At this stage of its development, PHP offers programmers a wide range of functions for dynamically generating images and working with them. In this article I will show you a technique for creating a class that will put watermarks on these same images. This class will work with two images: the original and the watermark. As an addition, a third parameter has been introduced - our class will contain an alpha variable. This will allow us to use an alpha channel for our watermark.

For reference

alpha channel: part of an image that stores information about the transparency of individual parts of the image, while color channels store information about the color of the image. IN graphic editors used to mask (protect from editing) some area of ​​the image. In some applications they are called a transparent mask.

The information found in the alpha channel most often represents highlighted areas - some shape or arrangement of colored areas. Storing an alpha channel in an image increases the file size by 1/3. RGB images can have up to 24 alpha channels. Bitmaps and indexed images cannot contain alpha channels.

Part One - Basics

Before we start writing the class itself, let's look at the functions that will be used in it. Here is their list:

# returns the width and height of the image imagesx() imagesy() # creates a new image true-color imagecreatetruecolor # returns an associative array with the keys red, green and blue (+ alpha channel) containing the corresponding values ​​for the specified color index imagecolorsforindex() # returns index of the color of a pixel at a specified location in the image imagecolorat() # draws a single pixel of the given color imagesetpixel() # returns index the index of the color in the image's palette, the identifier of the color (composed of its RGB components), and the index of the palette color of the image that is "closest" to RGB -value accordingly (this data is necessary for the imagesetpixel() function) imagecolorexact() imagecolorallocate() imagecolorclosest()

As you can see, php has enough functions to work with graphics. Even though the purpose of some of them is not entirely clear in theory, in practice everything is much simpler. Therefore, to figure out how to work with them, we will apply them in our class.

Choosing the path to the goal

Now that we have already decided on the goal of our “mini-project,” let’s go back a little and talk about ways to implement it.

To begin with, our application receives two images - the original image and the watermark itself. Next, we need to determine the dimensions of these images (width-width and height-height). We need this data to place the watermark in the center of the image (based on the assumption that the size of the watermark will be smaller than the image itself).

Then you will need to apply our watermark to the original image. To do this, we will need to add the colors of the (mathematically) overlaid images to obtain a third one.

And in the end, we will need to display the resulting image in the browser. IN in this case the picture will be opened directly from the source specified in the " tag "

I think the theory is already enough - the key points in it are revealed in sufficient detail. Now let's move on to writing the script.

Part two - writing a script

Let's start with the simplest thing - write a class that creates a file with a watermark. Let's call it "watermark" and write its code in the file "api.watermark.php". The “skeleton” of the class will be three functions:

The next step is to write code for the "watermark" class functions. We supplement the file "api.watermark.php" with the following lines of code:

# function that merges two source images into one function create_watermark($main_img_obj, $watermark_img_obj, $alpha_level = 100) ( # convert the alpha channel transparency value from % to tens $alpha_level/= 100; # calculate image dimensions (width and height ) $main_img_obj_w = imagesx($main_img_obj); $main_img_obj_h = imagesy($main_img_obj); $watermark_img_obj_w = imagesx($watermark_img_obj); $watermark_img_obj_h = imagesy($watermark_img_obj); # determining the coordinates of the image center $main_img_obj_min_x=floor(($main_ img_obj_w /2)-($watermark_img_obj_w/2)); $main_img_obj_max_x=ceil(($main_img_obj_w/2)+($watermark_img_obj_w/2)); $main_img_obj_min_y=floor(($main_img_obj_h/2)-($watermark_img_obj_h/2) ); $main_img_obj_max_y=ceil(($main_img_obj_h/2)+($watermark_img_obj_h/2)); # creating a new image $return_img = imagecreatetruecolor($main_img_obj_w, $main_img_obj_h); # let's go through the original image # "some code" # display image with watermark return $return_img; ) # end of function create_watermark()

Now let's take a closer look at the create_watermark() function.

First of all, we pass it three parameters:

# the original image to be watermarked $main_img_obj # the watermark itself must contain an alpha channel $watermark_img_obj # the alpha channel transparency value of the watermark, (0-100, default = 100) $alpha_level

(It's important to note that our function accepts images as objects, not just paths to them - but more on that later)

The next step is to create a new, true-color image with the same dimensions as the original image. This image (variable $return_img) will be used to combine information from the original images (drawing and watermark).

But before that, you still need to “go through” each of the two initial images and “merge” them into one. It’s just too early to do this - we are not ready for this yet. Instead, we'll post a "some code" comment and then fill that space with a section of code.

The end result is that our modified image will be displayed on the web page that requests it. Next, let's look at the remaining two auxiliary functions.

Part Three - Helper Functions

In addition to the create_watermark function, our watermark class contains two more functions. Let's continue source class with the following lines:

# averaging two colors taking into account the transparency of the alpha channel function _get_ave_color($color_a, $color_b, $alpha_level) ( return round((($color_a*(1-$alpha_level))+($color_b*$alpha_level))); ) # return the values ​​of the nearest RGB components of the new image function _get_image_color($im, $r, $g, $b) ( $c=imagecolorexact($im, $r, $g, $b); if ($c!=- 1) return $c; $c=imagecolorallocate($im, $r, $g, $b); if ($c!=-1) return $c; return imagecolorclosest($im, $r, $g, $ b); )

And now more details. Our first function "_get_ave_color" takes in the numeric values ​​of two colors and an alpha channel. It returns their average value. We need this function to determine the color that will be obtained when the pixels of two pictures are superimposed.

The second function "_get_image_color" splits the image into red (red), green (green) and blue (blue) components (rgb palette). Using built-in php functions to work with graphics (their description was at the beginning of the article), we get the closest color value for the new image.

In addition, several points are also checked. Firstly, if it was possible to obtain the exact value (variable $c), then it is returned from the function (return $c). Otherwise, an attempt is made to select a color using the imagecolorallocate() function. If this does not help achieve the result, then using the imagecolorclosest() function the closest color value (the most inaccurate) is simply returned.

Well, our class is almost ready. All that remains is to replace the “some code” comment in the “create_watermark” function with the following lines:

# walk through the image for($y = 0; $y< $main_img_obj_h; $y++) { for ($x = 0; $x < $main_img_obj_w; $x++) { $return_color = NULL; # определение истинного расположения пикселя в пределах # нашего водяного знака $watermark_x = $x - $main_img_obj_min_x; $watermark_y = $y - $main_img_obj_min_y; # выбор информации о цвете для наших изображений $main_rgb = imagecolorsforindex($main_img_obj, imagecolorat($main_img_obj, $x, $y)); # если наш пиксель водяного знака непрозрачный if ($watermark_x >= 0 && $watermark_x< $watermark_img_obj_w && $watermark_y >= 0 && $watermark_y< $watermark_img_obj_h) { $watermark_rbg = imagecolorsforindex($watermark_img_obj, imagecolorat($watermark_img_obj, $watermark_x, $watermark_y)); # использование значения прозрачности альфа-канала $watermark_alpha = round(((127-$watermark_rbg["alpha"])/127),2); $watermark_alpha = $watermark_alpha * $alpha_level; # расчет цвета в месте наложения картинок $avg_red = $this->_get_ave_color($main_rgb["red"], $watermark_rbg["red"], $watermark_alpha); $avg_green = $this->_get_ave_color($main_rgb["green"], $watermark_rbg["green"], $watermark_alpha); $avg_blue = $this->_get_ave_color($main_rgb["blue"], $watermark_rbg["blue"], $watermark_alpha); # using the received data, calculate the color index $return_color = $this->_get_image_color($return_img, $avg_red, $avg_green, $avg_blue); # if we can’t choose a color, then just take # a copy of the original pixel) else ( $return_color = imagecolorat($main_img_obj, $x, $y); ) # from the resulting pixels we draw a new image imagesetpixel($return_img, $x, $ y, $return_color); ) )

After writing such a significant part of the code, you can pause and take a closer look at its analysis.

The first thing our script does is traverse the image using two "for" loops. At the same time, the coordinates of each pixel of the watermark are also calculated.

Next, RGB information is searched for each pixel. If the current pixel is not in the intersection area of ​​the original image and the watermark, then our class only duplicates the pixel for the new image. If the pixel is located in the intersection area, we need to determine its color as a result of the overlay of the original image and the watermark.

To determine the color of the intersection area, we first need to obtain the value of the watermark RGB variable using the information we obtained in the "for" loops. Then, using the "_get_ave_color" function, the average color value for the new image is determined. Next comes the "_get_image_color" function to determine the color scheme that will be used by the "return_img" function.

As a result, after the “for” loops complete, we have a finished image with a watermark.

Now let's check our class in action.

Part four - test drive

To get started, we need two files. Let's call the first one "watermark_test.php" and place the following code in it:



The purpose of this file is very simple: it displays the original (main.jpg) and the resulting (watermark.png, with a watermark) images in the browser.

As you can see, our second image (watermark.png) refers to the php file image.php, not the image file. This link takes the form of a GET request, where the values ​​of two variables are transferred to the php file: $main and $watermark.

Let's call the second file "image.php" and place the following code in it:

create_watermark($main_img_obj, $watermark_img_obj, 66); # display our resulting image in the browser - # but first let it know that it is a jpeg file header("Content-Type: image/jpeg"); header("Content-Disposition: inline; filename=" . $_GET["src"]); imagejpeg($return_img_obj, "", 50); ?>

Well, we've reached the finale. (ZIP, 47.6Kb)

If you notice an error, select a piece of text and press Ctrl+Enter
SHARE: