Php adding watermark to image

How To Add Watermark in Images Using PHP – Source Code

Hello programmers in this PHP Tutorial I’m gonna show you how to add watermark to image using PHP. I will create a PHP file which will process two images, One image will be our main image and another one is our watermark image. I will create a PHP file which will take these two images and the watermark image will be placed on the main image.

You might also be inteested in How To Add text to image in PHP

Generally, a watermark image is used as a logo or brand identification image. This watermark is generally transparent type. But our main target in this tutorial is to learn how to add a watermark image to another image using PHP.

Читайте также:  Javascript for android browser

How to add watermark to image using PHP with Explanation

Adding watermark to images in PHP is not a hard task to do. what you need to know is some PHP function to work with images. Those functions are –

imagecreatefrompng() PHP function
imagesx() and imagesy() PHP function
imagecreatetruecolor() PHP function
imagecreatefromjpeg() PHP function
getimagesize() PHP function
imagecopymerge() PHP function

You just need to have some basic knowledge of these functions and some basic idea on what these functions do.

PHP code to add watermark to any image

The below code will process two images and display the newly created watermarked image from those two images on your browser while running this code.

Code Explanation Line By Line of Adding Watermark to images in PHP

Just save the above PHP code as a PHP file and in the directory suppose I have two image files. One is image.jpg which is our main image. And another one is watermark.png .

The watermark.png file is going to be used as a watermark here on the image image.jpg .

So what I am going to do is simply took our main image and then will put watermark.png image on that main image.

So before going to explain how we can do this, I would like to tell you what is the purpose of those above functions listed and used in this PHP code.

header('Content-type: image/jpeg')

This is our Content-type of this PHP file. Many of us do not use this content type if he or she is intending to use HTML content type for the page. Because by default PHP mark this file as HTML page type.

But here we want that, when I will run my PHP file I wish that I will get my watermarked image on my browser page. That’s why I have set header(‘Content-type: image/jpeg’); as I wish to have an image type page.

Here, $source variable refers my main image file. You can use your filename followed by your file path. My main image’s filename is image.jpg

Functions used in this tutorial of adding watermark to images using PHP

$watermark=imagecreatefrompng('watermark.png');

This function takes a filename as a parameter and Returns an image resource identifier on success, FALSE on errors.
You can use URL too if fopen wrappers have been enabled.

$watermark_height= imagesy($watermark);

This function imagesy() returns the height of an image resource. But remember the resource image must be get returned by one of the image creation functions in PHP.

$watermark_width=imagesx($watermark);

This PHP function imagesx() is very much similar to the previous one. But it returns the width of an image resource.

In both the lines, our image resource is our watermark.png image file. We have got the height and width of that image file.

$image=imagecreatetruecolor($watermark_width, $watermark_height)

By this line, we create a new true color image from our watermark image height and width.

This is actually a black image of the same height and width of watermark.png file.

imagecreatefromjpeg() function in PHP almost do the same job as imagecreatefrompng() function. But here our source image resource fill is jpeg type.

imagecopymerge($image, $watermark, $x, $y, 0, 0, $watermark_width, $watermark_width, 100);

Now this line is very much important to add watermark to image using PHP.

In this function, we have several parameters.

The first parameter is $image, this is the place where we can put our main image and just after it we have to use our second parameter. The second parameter is for our watermark.png file.

$x and $y might be confusing for you. This is nothing but the position where we gonna keep our watermark image.

Then 0 and 0 these are the initial or starting position of our x and y-axis.

And the last parameter is known as pct. This is similar two opacity and this value varies from zero to hundred.

This is the function which gonna give us the output watermarked final image.

How to save the watermarked image created by this PHP code

To save this image in your local drive path just simply add another parameter like the below

imagejpeg($image,'watermarked.jpg'); 

This function will create a new file watermarked.jpg which is nothing but the watermarked image. After running this PHP code on your server you can check that in the same path a new file will be generated if everything goes perfect. And the new file is nothing but your final output of this program.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Add text or image Watermark on image and PDF files

License

ajaxray/php-watermark

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Add text or image Watermark on image and PDF using PHP and ImageMagick.

PHP ImageMagick extension is not required.

Add as a dependency with composer

$ composer require ajaxray/php-watermark

Or download latest version as a Zip file.

$ composer require ajaxray/php-watermark:v0.1.2

Also you should check older readme file for PHP version

 // Initiate with source image or pdf $watermark = new Watermark('/path/to/source.jpg'); // Customize some options (See list of supported options below) $watermark->withText('ajaxray.com') ->setFontSize(48) ->setRotate(30) ->setOpacity(.4) ->write('path/to/output.jpg'); // Watermark with Image $watermark->withImage('path/to/logo.png') ->setPosition(Watermark::POSITION_BOTTOM_RIGHT) ->setStyle(Watermark::STYLE_IMG_DISSOLVE) ->write('path/to/output.jpg');

If output file name is skipped for Watermark::write() function, the source file will be overridden.

The table below shows customization options and their support matrix. Listed functions should be called on an object of Ajaxray\PHPWatermark\Watermark . Checkmark column titles means the following —

  • Txt-Img: Watermarking with text on Image (sample, sample-tiled)
  • Img-Img: Watermarking with Image on Image (sample)
  • Txt-PDF: Watermarking with text on PDF (sample)
  • Img-PDF: Watermarking with Image on PDF (sample)
Function Value Txt-Img Img-Img Txt-PDF Img-PDF
setFont(‘Arial’) string; Font Name
setFontSize(36) int; Font size
setOpacity(.4) float; between 0 (opaque) to 1 (transparent)
setRotate(245) int; between 0 to 360
setPosition($position) int; One of Watermark::POSITION_* constants
setOffset(50, 100) int, int; X and Y offset relative to position
setStyle($style) int; One of Watermark::STYLE_* constants
setTiled() boolean; (default true )
setTileSize(200, 150) int, int; Width and Height of each tile

BTW, all the samples linked above are the results of these examples. You may generate them yourself just by running example scripts from command line —

$ php vendor/ajaxray/php-watermark/examples/example_img.php $ php vendor/ajaxray/php-watermark/examples/example_pdf.php

Then you should get the result files in vendor/ajaxray/php-watermark/examples/img and vendor/ajaxray/php-watermark/examples/pdf directories.

Something unexpected? Debug! 🐞 🔫

If anything unexpected happened, try to debug the issue.

    First step is to check if PHP is configured to display errors. Alternatively you may add these lines at the top of your script.

ini_set('display_errors', 1); error_reporting(E_ALL);
  • The file path mentioned in the second argument of Watermark::withText() and Watermark::withImage() methods.
  • Parent of the source file itself if no separate destination mentioned in above methods.
  • To see the list of supported font names in your system, run convert -list font on command prompt
  • Remember to set appropriate output file extension (e,g, .pdf for pdf files)
  • If possible, use absolute path for files to avoid various mistakes.
  • STYLE_IMG_* constants are for Image watermarks and Watermark::STYLE_TEXT_* are for text.
  • Default text style ( Watermark::STYLE_TEXT_BEVEL ) is expected to be visible on any background. Use other text styles only on selective backgrounds.
  • UnitTest are executed and all green against PHP 5.6 and PHP 7.1 using PHPUnit 5.7.5
  • I’v tested all intended functionality with ImageMagick 7.0.4-6 Q16 x86_64 and GPL Ghostscript 9.20 installed.

Important Update for PDF watermarking:

When using the imagemagick + ghostscript extraction and joining pdf pages, it has a few drawbacks including file-size issue. Many developers were asking for a solution about the file size and PDF quality since releasing of this library. So, I’ve created a command line tool for PDF watermarking that will work without converting pages into images. As a result, you’ll get better PDF quality and dramatically smaller file size.

Please note that, it’s not a PHP library. So you’ve to use it using exec, shell_exec or Symfony Process Component.

«This is the Book about which there is no doubt, a guidance for those conscious of Allah» — Al-Quran

Источник

Php adding watermark to image

В этом разделе помещены уроки по PHP скриптам, которые Вы сможете использовать на своих ресурсах.

Фильтрация данных с помощью zend-filter

Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.

Контекстное экранирование с помощью zend-escaper

Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.

Подключение Zend модулей к Expressive

Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.

Совет: отправка информации в Google Analytics через API

Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.

Подборка PHP песочниц

Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.

Совет: активация отображения всех ошибок в PHP

При поднятии PHP проекта на новом рабочем окружении могут возникнуть ошибки отображение которых изначально скрыто базовыми настройками. Это можно исправить, прописав несколько команд.

Источник

Оцените статью