Portal for car enthusiasts

php overlay watermark. Choosing a watermarking method

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

Introduction

At this stage of its development, PHP offers a wide range of functions for programmers to dynamically generate and work with images. In this article, I'll show you how to create a class that will watermark these same images. This class will work with two images: original and 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 (alpha-channel): part of the image that stores information about the transparency of individual sections of the image, while color channels store information about the color of the image. In graphic editors, it is used to mask (protect from editing) a certain area of ​​the image. In some applications, they are called a transparent mask.

The information found in the alpha channel most often represents highlights - some shape or arrangement of colored areas. Keeping the alpha channel in the 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 - the 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 true-color image 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 the color index of a pixel at a specified location in an image imagecolorat() # draws a single pixel of the given color imagesetpixel() # returns the index of the image's paletted color index, the color id (composed of RGB components), and the paletted color index of the image that is "closest" to RGB -value respectively (this data is needed for the imagesetpixel() function) imagecolorexact() imagecolorallocate() imagecolorclosest()

As you can see, php has enough functions for working with graphics. Although 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.

First, 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 (assuming that the size of the watermark will be smaller than the image itself).

Then we will need to overlay our watermark on the original image. To do this, we need to add the colors (mathematically) of the overlay images to get the third one.

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

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

Part two - writing the script

Let's start with the simplest - let's 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 the code for the functions of the "watermark" class. We supplement the file "api.watermark.php" with the following lines of code:

# a 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); # determine image center coordinates $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)); # create a new image $return_img = imagecreatetruecolor($main_img_obj_w, $main_img_obj_h); # walk through the original image # "some code" # display watermarked image return $return_img; ) # end of create_watermark() function

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

First of all, we pass three parameters to it:

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

(It's important to note that our function accepts images as objects, not just as 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 ($return_img variable) will be used to combine the information from the original images (image and watermark).

But before that, you still need to "walk" through each of the two original images and "merge" them into one. It's just too early to do this - we are not ready for this yet. Instead, we'll place a "some code" comment, and then add a piece of code to that space.

The final step is to display our modified image on the web page that requests it. Next, consider the remaining two auxiliary functions.

Part Three - Helper Functions

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

# average 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 in more detail. Our first "_get_ave_color" function takes the numerical 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 drawings are superimposed.

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

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

Well, our class is almost ready. It remains only 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 you can't choose a color, then just take # a copy of the original pixel ) else ( $return_color = imagecolorat($main_img_obj, $x, $y); ) # draw a new image from the received pixels imagesetpixel($return_img, $x, $ y, $return_color); ) )

After writing such a significant part of the code, you can pause and dwell on its analysis in more detail.

Our script first traverses the image using two "for" loops. In parallel, the coordinates of each pixel of the watermark are also calculated.

Next, the RGB information is searched for each pixel. If the current pixel is not in the area where the original image and the watermark intersect, 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 get the value of the watermark's RGB variable using the information we got 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 completion of the "for" loops, we have a finished image with a watermark.

And now let's check our class in action.

Part four - test drive

To get started, we need two files. Let's name 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, watermarked) images in the browser.

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

Let's name 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 it's a jpeg file header("Content-Type: image/jpeg"); header("Content-Disposition: inline; filename=" . $_GET["src"]); imagejpeg($return_img_obj, "", 50); ?>

Well, here we come to the final. (ZIP, 47.6Kb)

There are a large number of images on the Internet, which, as a rule, are uploaded by site owners or site users. Depending on the relevance, the image may migrate from site to site. Not to mention copyright, not every site owner may like the fact that images from his site are copied on other resources. As a means of combating the banal copying of site images, it was invented to impose watermarks on images, indicating that the image belongs to a particular resource. This can be especially true for sites that have a large number of unique images.

Let's look at a code example that demonstrates the imposition of a watermark on uploaded images.

So, the main settings are contained in the form of constants, and they go first in the code:

// watermark image path define("WATERMARK_OVERLAY_IMAGE", "/lab/watermark/watermark.png"); // Compression, range 0-100 (affects image quality) define("WATERMARK_OUTPUT_QUALITY", 100); // source images folder define("UPLOADED_IMAGE_DESTINATION", "/lab/watermark/upload/src/"); // folder with processed images define("WATERMARK_IMAGE_DESTINATION", "/lab/watermark/upload/");

On the page, we will place an image upload form that will be used to send images to the server.
Form code:

Choose an image file:
original image
"style="max-width: 300px;" />
Image with watermark
"style="max-width: 300px;" />

Well, now the most important thing is the functions for image processing. Place these functions before displaying the form on the page.

Two key functions, with the help of one the image is uploaded to the server, with the help of the other a watermark is superimposed. Perhaps, the comments to the functions are described in more than detail, and it would be superfluous to write the same here.

If you want to add a watermark to a photo without bothering with image editors or adding it while uploading photos to the server, then this lesson 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 that you will 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 a png image and get its dimensions:

// create a png watermark $watermark = imagecreatefrompng("watermark.png"); // get 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 via a form. We act as follows:

// create a jpg image $image_path = "original.jpg"; $image = imagecreatefromjpeg($image_path); // get image dimension $size = getimagesize($image_path);

Now we need to place a watermark on the image:

// put the watermark at the bottom right. 5px padding $dest_x = $size - $watermark_width - 5; $dest_y = $size - $watermark_height - 5;

Then we'll set the blending options for both images:

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

In the end, 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 take away:

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

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

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

Header("content-type: image/jpeg"); // get image name via GET $image = $_GET["image"]; // create a watermark $watermark = imagecreatefrompng("watermark.png"); // get watermark height and width $watermark_width = imagesx($watermark); $watermark_height = imagesy($watermark); // create jpg from 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); // put 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 memory imagedestroy($image); imagedestroy($watermark);

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

You take a big risk when you publish your images and videos on the Internet, as your content can easily be copied to hundreds of other sites. It would not be great to find your picture for the news, for example, on which you worked hard, on another site without indicating the source, that is, your site, right? You will be upset, to put it mildly, and if it was not a simple picture for the news, but a complex work in Photoshop, to say that you are 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 watermark to each uploaded image in order to secure it. CEH can be the logo of your site or company, beautifully and aesthetically placed on the 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 watermark define("WATERMARK_OUTPUT_QUALITY", 100); // The quality of the received image from the watermark. 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 watermark

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 "Upload failed!"; )

For example, if the image being loaded was:

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

In this example, the uploaded image is saved in one folder, and the image that has been digitally watermarked in another, so that you always have access to the original images, but, of course, you should place images from the CEH on the site.

(178.4 KiB, 989 hits)