GithubHelp home page GithubHelp logo

ajaxray / php-watermark Goto Github PK

View Code? Open in Web Editor NEW
129.0 8.0 44.0 1.73 MB

Add text or image Watermark on image and PDF files

License: MIT License

PHP 93.99% Dockerfile 6.01%
php php56 watermark watermark-image image-manipulation imagemagick imagemagick-wrapper php7 php8 pdf

php-watermark's Introduction

PHPWatermark

SensioLabsInsight Latest Stable Version Build Status Coverage Status Total Downloads License

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

Pre-requisite

PHP ImageMagick extension is not required.

Installation

Add as a dependency with composer

$ composer require ajaxray/php-watermark

Or download latest version as a Zip file.

For PHP versions >= 5.6 to <8 use v0.1.2

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

Also you should check older readme file for PHP version <8

How to use?

 <?php
    // 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.

Customization options

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)

⌛ = coming soon!

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.

  1. 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);
  2. A common reason of not getting expected result is mistakes in filepaths. You may try logging / printing source and destination file paths.
  3. Check the permission of the parent directory of destination path. Destination directory indicates -
    • 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.
  4. There is Watermark::setDebug() method which will make Watermark object to return imagemagick command instead of executing it. Then, you may run the output manually to check if there is any error in underlying imagemagick commands.

Notes:

  • 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.

https://github.com/ajaxray/markpdf

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-watermark's People

Contributors

ajaxray avatar maizergomes avatar peter279k avatar rahilwazir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

php-watermark's Issues

not support php 7.3

Parse error: syntax error, unexpected 'string' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in src\Ajaxray\PHPWatermark\Watermark.php on line 31

Text color

Hi,

Is there any plan to update this package to have text color functionality?

Actually i tried to change rgba color in this function getDuelTextColor but unfortunately it does't work.

Can you give me a hand in this if you don't plan to update this package soon.

Local Development Issues

I am getting the code to work exactly as I'd hoped on my live server. I am using wamp locally, and it seems that the file isn't writing even though I'm using chmod on the directory and setting it to 0777. Is there any reason I should think of why your code wouldn't write a new file on a windows server?

Thanks!
Kyle

Contrast / Negative effect

Hi,

I have a transparent watermark which is basically a rectangle with white borders and the letters of my website inside written in white as well. The rest is transparency. It works very well but as you can imagine, when I apply this watermark on bright images, my watermark doesn't show up, it's almost invisible.

It would be nice if we could have an option to adjust the watermark image contrast/colors depending of the background, just like mix-blend-mode in CSS: https://css-tricks.com/almanac/properties/m/mix-blend-mode/

To make it short: a watermark that adapts to the background.

How can use this library with the code i already have?

        $data = new File();
        $data->name = $request->input('name');
        $this->validate($request, ['file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ] //only allow this type extension file.
        );
        $file = $request->file('file');
        $ext = $file->getClientOriginalExtension();
        $newName = rand(100000, 1001238912) . "." . $ext;
        $file->move('uploads/file', $newName);
        $data->file = $newName;
        $data->save();

I am new to Laravel, what I'm doing here is to get a new name for the file and save it to the db as well as to the uploads/file folder. I want to be able to watermark the image i upload as well as retain the naming convention. Example name of the file could be 426240098.jpeg. I'll appreciate your help

PDF not being generated

Just ran the examples provided here and the pdfs are simply not being generated. Nothing happens at all. No erros and no exceptions being thrown.

Can someone give me a light?

UPDATE:

So, checking my apache error log, it turns out I have this error

sh: convert: command not found

Which is odd, because I can run convert from bash

Ghostscript

I have both install ghostscript and ImageMagick, and i used laravel framework. When i used image watermark is works very well, but when i used pdf watermark. it seems nothing has happen. Am i do wrong?

This is my code :

if($id_watermark->fileext == 'image/jpeg' || $id_watermark->fileext == 'image/png') { /* Watermarking with Text */ $watermark = new Watermark('upload/'.$id_watermark->files); $watermark->setTiled() ->setTileSize(300, 300) ->setFontSize(24) ->setRotate(330) ->setOffset(60, 0); $text = "Verified"; $watermark->withText($text, 'upload/'.$id_watermark->files); } elseif($id_watermark->fileext == 'application/pdf') { /* Watermarking with Text */ $watermark = new Watermark('upload/'.$id_watermark->files); $watermark->setFont('Arial'); $watermark->setFontSize(18); $watermark->setRotate(345); $watermark->setOffset(20, 60); $watermark->setPosition(Watermark::POSITION_BOTTOM_RIGHT); $text = "Verified"; $watermark->withText($text, 'upload/'.$id_watermark->files); }
code when the extension is pdf is not working. Is it any way to properly used ghostscript?

pdf quality is distorted,

Hi friend

I have used your library for pdf watermark and it would be working well but pdf quality is distorted, can you please guide me how to make it same as original with watermark.

Thanks!
Jigs

Apply watermark on certain pages

Hi, I was wondering if it's possible to apply watermarks to specific pages instead of all? I have a 500+ page PDF and I'd like to apply the watermark on only the first page. Ideally, I should be able to get the total number of pages and if it exceeds a certain number (say, 20), I apply the watermark on only the first page.

Png watermark transparency.

I have a trouble which described here
http://www.imagemagick.org/discourse-server/viewtopic.php?t=31549
When I use a png image as a watermark I get gray background as a result.
So I propose to make changes in the method getMarkerOpacity of class PDFCommandBuilder:
replace strings

$opacity = $this->getOpacity() * 100;
return "-alpha set -channel A -evaluate set {$opacity}%";

with strings

$opacity = $this->getOpacity();
return "-alpha set -channel A -evaluate multiply {$opacity}";

function withImage() return false

I am using this package to apply watermark on pdf files bu watermark does not merged with pdf file, instead withImage() function return false.

  $watermark = 'images/watermark.png';

     if ($model->extension == 'pdf') {
        $pdf = new Watermark($fileName); // $fileName is string that contain path to pdf file
        $pdf->withImage($watermark);
     }

The problem is, it does not throw any error like file not exist or etc. it just returns false.

Help with basic installation

Hi,

I'm using the script without composer. I downloaded the archive and tried to run the example_img.php.

I had to change the include 'vendor/autoload.php'; since there's no autoload.php file (I suppose this come from Composer)

I used the following include :

include '../src/Ajaxray/PHPWatermark/Watermark.php';

I get the following error:

Uncaught Error: Class 'Ajaxray\PHPWatermark\CommandBuilders\ImageCommandBuilder' not found in /src/Ajaxray/PHPWatermark/Watermark.php:112

Any ideas on what I'm doing wrong? I have not modified any other files.

Thanks!

File Size Balloons and PDF gets Corrupted

In testing, this package has been working flawlessly. However, I got the final document we're going to use live. For some reason, that document doesn't work.

The original PDF is 853KB. However when I try and watermark it with my name and email, it blows up to like 20MB in size, and the outputted file is corrupted and can't be open. Please note, nothing about this code changes except pointing to a different PDF.

$documentPath = BEDROCK_CONFIG_DIR . '/1519939315.XeevRAl27BGXn9MAVctvCYBATWxL88sKm04YU1e5.pdf';
      $inputFile = '1519939315.XeevRAl27BGXn9MAVctvCYBATWxL88sKm04YU1e5.pdf';
      $watermark = new Watermark(BEDROCK_CONFIG_DIR . '/1519939315.XeevRAl27BGXn9MAVctvCYBATWxL88sKm04YU1e5.pdf');

      // set watermark text
      $text = $row->first_name . " " . $row->last_name . " \r\n " . $row->email;

      // Watermark with text
      $watermark->setFont('AvantGarde-BookOblique');
      $watermark->setFontSize(24);
      $watermark->setRotate(345);
      $watermark->setOffset(0, 0);
      $watermark->setOpacity(.2);
      $watermark->setPosition(Watermark::POSITION_CENTER);

      // write file to hd
      $outputFile = BEDROCK_CONFIG_DIR . '/output/' . $inputFile;
      $watermark->withText($text, $outputFile);

I am not getting any errors in the console other than it takes a long time obviously. Is there any specific way I need to save PDFs, or format them in a specific way?

EDIT: The PDFs are just word documents I click save as PDF or print to PDF. The latest test I did this way created a PDF 2MB. When I ran the above script over it, the output was 13MB (Only putting my name & email as you can see).

In this last example, it opened OK, but why did adding my name & email to each page (81 pages), increase the size by 11MB?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.