search
HomeBackend DevelopmentPHP TutorialPHP watermark code supports text and image watermarks_PHP tutorial

PHP watermark code supports text and image watermarks_PHP tutorial

Jul 13, 2016 am 10:32 AM
phpcodeaddandpicturesupportletterwatermarkofkindbackgroundset uptransparency

PHP adds picture watermark and text watermark code. PHP adds watermark class. It supports the transparency setting of text and picture watermarks and the transparent background of watermark pictures. I wrote a class myself, because it needs to be used in a set of CMS I developed. People on the Internet always feel that it is not easy to use. I hope everyone likes this class. The usage method of the class is attached.

 001

 002class WaterMask{

 003 public $waterType = 1; //Watermark type: 0 is text watermark, 1 is picture watermark

 004 public $pos = 0; //Watermark position

 005 public $transparent = 45; //Watermark transparency

 006 public $waterStr = 'www.codefans.net'; //Watermark text

 007 public $fontSize = 16; //Text font size

 008 public $fontColor = array(255,0,255); //Watermark text color (RGB)

 009 public $fontFile = 'AHGBold.ttf';//Font file

 010 public $waterImg = 'logo.png';//Watermark image

 011 private $srcImg = '';//Pictures that need to be watermarked

 012 private $im = '';//image handle

 013 private $water_im = '';//Watermark image handle

 014 private $srcImg_info = '';//Picture information

 015 private $waterImg_info = '';//Watermark image information

 016 private $str_w = '';//Watermark text width

 017 private $str_h = '';//Watermark text height

 018 private $x = '';//Watermark X coordinate

 019 private $y = '';//watermark y coordinate

 020 function __construct($img) {

 021 $this->srcImg = file_exists($img) $img : die('"'.$img.'" Sorry, the watermark file does not exist!');

 022}

 023 private function imginfo() {//Get the watermark image information and load it.

 024 $this->srcImg_info = getimagesize($this->srcImg);

 025 switch ($this->srcImg_info[2]) {

 026 case 3:

 027 $this->im = imagecreatefrompng($this->srcImg);

 028 break 1;

 029 case 2:

 030 $this->im = imagecreatefromjpeg($this->srcImg);

 031 break 1;

 032 case 1:

 033 $this->im = imagecreatefromgif($this->srcImg);

 034 break 1;

 035 default:

 036 die('Watermark image ('.$this->srcImg.') The format of the watermark image is incorrect, please choose an image in PNG, JPEG, or GIF format.');

 037}

 038}

 039 private function waterimginfo() {//Get the watermark image and load it.

 040 $this->waterImg_info = getimagesize($this->waterImg);

 041 switch ($this->waterImg_info[2]) {

 042 case 3:

 043 $this->water_im = imagecreatefrompng($this->waterImg);

 044 break 1;

 045 case 2:

 046 $this->water_im = imagecreatefromjpeg($this->waterImg);

 047 break 1;

 048 case 1:

 049 $this->water_im = imagecreatefromgif($this->waterImg);

 050 break 1;

 051 default:

 052 die('The format of the watermark image ('.$this->srcImg.') is incorrect, only PNG, JPEG, and GIF are supported.');

 053}

 054}

 055 private function waterpos() {//Watermark position algorithm

 056 switch ($this->pos) {

 057 case 0: //Random position

 058 $this->x = rand(0,$this->srcImg_info[0]-$this->waterImg_info[0]);

 059 $this->y = rand(0,$this->srcImg_info[1]-$this->waterImg_info[1]);

 060 break 1;

 061 case 1: //Top left

 062 $this->x = 0;

 063 $this->y = 0;

 064 break 1;

 065 case 2: //upper middle

 066 $this->x = ($this->srcImg_info[0]-$this->waterImg_info[0])/2;

 067 $this->y = 0;

 068 break 1;

 069 case 3: //Top right

 070 $this->x = $this->srcImg_info[0]-$this->waterImg_info[0];

 071 $this->y = 0;

 072 break 1;

 073 case 4: //center left

 074 $this->x = 0;

 075 $this->y = ($this->srcImg_info[1]-$this->waterImg_info[1])/2;

 076 break 1;

 077 case 5: //中中

 078 $this->x = ($this->srcImg_info[0]-$this->waterImg_info[0])/2;

 079 $this->y = ($this->srcImg_info[1]-$this->waterImg_info[1])/2;

 080 break 1;

 081 case 6: //Center right

 082 $this->x = $this->srcImg_info[0]-$this->waterImg_info[0];

 083 $this->y = ($this->srcImg_info[1]-$this->waterImg_info[1])/2;

 084 break 1;

 085 case 7: //Lower left

 086 $this->x = 0;

  087 $this->y = $this->srcImg_info[1]-$this->waterImg_info[1];

  088 break 1;

  089 case 8: //下中

  090 $this->x = ($this->srcImg_info[0]-$this->waterImg_info[0])/2;

  091 $this->y = $this->srcImg_info[1]-$this->waterImg_info[1];

  092 break 1;

  093 default: //下右

  094 $this->x = $this->srcImg_info[0]-$this->waterImg_info[0];

  095 $this->y = $this->srcImg_info[1]-$this->waterImg_info[1];

  096 break 1;

  097 }

  098 }

  099 private function waterimg() {

  100 if ($this->srcImg_info[0] waterImg_info[0] || $this->srcImg_info[1] waterImg_info[1]){

  101 die('水印比原图大!');

  102 }

  103 $this->waterpos();

  104 $cut = imagecreatetruecolor($this->waterImg_info[0],$this->waterImg_info[1]);

  105 imagecopy($cut,$this->im,0,0,$this->x,$this->y,$this->waterImg_info[0],$this->waterImg_info[1]);

  106 $pct = $this->transparent;

  107 imagecopy($cut,$this->water_im,0,0,0,0,$this->waterImg_info[0],$this->waterImg_info[1]);

  108 imagecopymerge($this->im,$cut,$this->x,$this->y,0,0,$this->waterImg_info[0],$this->waterImg_info[1],$pct);

  109 }

  110 private function waterstr() {

  111 $rect = imagettfbbox($this->fontSize,0,$this->fontFile,$this->waterStr);

  112 $w = abs($rect[2]-$rect[6]);

  113 $h = abs($rect[3]-$rect[7]);

  114 $fontHeight = $this->fontSize;

  115 $this->water_im = imagecreatetruecolor($w, $h);

  116 imagealphablending($this->water_im,false);

  117 imagesavealpha($this->water_im,true);

  118 $white_alpha = imagecolorallocatealpha($this->water_im,255,255,255,127);

  119 imagefill($this->water_im,0,0,$white_alpha);

  120 $color = imagecolorallocate($this->water_im,$this->fontColor[0],$this->fontColor[1],$this->fontColor[2]);

  121 imagettftext($this->water_im,$this->fontSize,0,0,$this->fontSize,$color,$this->fontFile,$this->waterStr);

  122 $this->waterImg_info = array(0=>$w,1=>$h);

  123 $this->waterimg();

  124 }

  125 function output() {

  126 $this->imginfo();

  127 if ($this->waterType == 0) {

  128 $this->waterstr();

  129 }else {

  130 $this->waterimginfo();

  131 $this->waterimg();

  132 }

  133 switch ($this->srcImg_info[2]) {

  134 case 3:

  135 imagepng($this->im,$this->srcImg);

  136 break 1;

  137 case 2:

  138 imagejpeg($this->im,$this->srcImg);

  139 break 1;

  140 case 1:

  141 imagegif($this->im,$this->srcImg);

  142 break 1;

  143 default:

  144 die('原因未知:水印添加失败!');

  145 break;

  146 }

  147 imagedestroy($this->im);

  148 imagedestroy($this->water_im);

  149 }

  150}

  151?>

  PHP生成水印类用法:

  view sourceprint?01

  02$obj = new WaterMask($imgFileName);

  03$obj->$waterType = 1;//水印类型:0为文字水印、1为图片水印

  04$obj->$transparent = 45;//水印透明度

  05$obj->$waterStr = 'www.codefans.net';//水印文字

  06$obj->$fontSize = 16;//字体大小

  07$obj->$fontColor = array(255,0,255);//水印文字颜色(RGB值)

  08$obj->$fontFile = = 'AHGBold.ttf'; //字体名称

  09$obj->output(); //输出水印图片

  10?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/755612.htmlTechArticlePHP adds picture watermark and text watermark code, PHP adds watermark class, supports transparency setting and watermark of text and picture watermark The picture background is transparent. A class I wrote because I developed a class...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools