search
HomeBackend DevelopmentPHP TutorialPHP image watermark code, add text watermark and image watermark to PHP images

  1. /**

  2. * Add watermark class, support transparency setting of text and picture watermarks, and transparent background of watermark pictures.
  3. * Usage: (php text watermark effect)
  4. * $obj = new WaterMask($imgFileName); //Instantiate the object
  5. * $obj->$waterType = 1; //Type: 0 is text watermark, 1 is Image watermark
  6. * $obj->$transparent = 45; //Watermark transparency
  7. * $obj->$waterStr = 'bbs.it-home.org'; //Watermark text
  8. * $obj->$ fontSize = 16; //Text font size
  9. * $obj->$fontColor = array(255,0255); //Watermark text color (RGB)
  10. * $obj->$fontFile = = 'AHGBold.ttf' ; //Font file
  11. * $obj->output(); //The output watermark image file overwrites the input image file
  12. */
  13. class WaterMask{
  14. public $waterType = 1; //Watermark type: 0 is text watermark, 1 is picture watermark
  15. public $pos = 0; //Watermark position
  16. public $transparent = 45; //Watermark transparency
  17. public $waterStr = 'bbs.it-home.org'; //Watermark text
  18. public $fontSize = 16; //Text font Size
  19. public $fontColor = array(255,0,255); //Watermark text color (RGB)
  20. public $fontFile = 'AHGBold.ttf'; //Font file
  21. public $waterImg = 'logo.png'; //Watermark Picture
  22. private $srcImg = ''; //Picture that needs to be watermarked
  23. private $im = ''; //Picture handle
  24. private $water_im = ''; //Watermark picture handle
  25. private $srcImg_info = ''; / /Picture information
  26. private $waterImg_info = ''; //Watermark picture information
  27. private $str_w = ''; //Watermark text width
  28. private $str_h = ''; //Watermark text height
  29. private $x = ''; //Watermark $img) ? $img : die('"'.$img.'" The source file does not exist!');
  30. }
  31. private function imginfo() { //Get the information of the image that needs to be watermarked and load the image .
  32. $this->srcImg_info = getimagesize($this->srcImg);
  33. switch ($this->srcImg_info[2]) {
  34. case 3:
  35. $this->im = imagecreatefrompng($this-> ;srcImg);
  36. break 1;
  37. case 2:
  38. $this->im = imagecreatefromjpeg($this->srcImg);
  39. break 1;
  40. case 1:
  41. $this->im = imagecreatefromgif($this ->srcImg);
  42. break 1;
  43. default:
  44. die('The format of the original image ('.$this->srcImg.') is wrong, only PNG, JPEG, and GIF are supported.');
  45. }
  46. }
  47. private function waterimginfo() { //Get the information of the watermark image and load the image.
  48. $this->waterImg_info = getimagesize($this->waterImg);
  49. switch ($this->waterImg_info[2]) {
  50. case 3:
  51. $this->water_im = imagecreatefrompng($this-> ;waterImg);
  52. break 1;
  53. case 2:
  54. $this->water_im = imagecreatefromjpeg($this->waterImg);
  55. break 1;
  56. case 1:
  57. $this->water_im = imagecreatefromgif($this ->waterImg);
  58. break 1;
  59. default:
  60. die('The watermark image ('.$this->srcImg.') is in the wrong format, only supports PNG, JPEG, and GIF.');
  61. }
  62. }
  63. private function waterpos() { //水印位置算法
  64. switch ($this->pos) {
  65. case 0: //随机位置
  66. $this->x = rand(0,$this->srcImg_info[0]-$this->waterImg_info[0]);
  67. $this->y = rand(0,$this->srcImg_info[1]-$this->waterImg_info[1]);
  68. break 1;
  69. case 1: //上左
  70. $this->x = 0;
  71. $this->y = 0;
  72. break 1;
  73. case 2: //上中
  74. $this->x = ($this->srcImg_info[0]-$this->waterImg_info[0])/2;
  75. $this->y = 0;
  76. break 1;
  77. case 3: //上右
  78. $this->x = $this->srcImg_info[0]-$this->waterImg_info[0];
  79. $this->y = 0;
  80. break 1;
  81. case 4: //中左
  82. $this->x = 0;
  83. $this->y = ($this->srcImg_info[1]-$this->waterImg_info[1])/2;
  84. break 1;
  85. case 5: //中中
  86. $this->x = ($this->srcImg_info[0]-$this->waterImg_info[0])/2;
  87. $this->y = ($this->srcImg_info[1]-$this->waterImg_info[1])/2;
  88. break 1;
  89. case 6: //中右
  90. $this->x = $this->srcImg_info[0]-$this->waterImg_info[0];
  91. $this->y = ($this->srcImg_info[1]-$this->waterImg_info[1])/2;
  92. break 1;
  93. case 7: //下左
  94. $this->x = 0;
  95. $this->y = $this->srcImg_info[1]-$this->waterImg_info[1];
  96. break 1;
  97. case 8: //下中
  98. $this->x = ($this->srcImg_info[0]-$this->waterImg_info[0])/2;
  99. $this->y = $this->srcImg_info[1]-$this->waterImg_info[1];
  100. break 1;
  101. default: //下右
  102. $this->x = $this->srcImg_info[0]-$this->waterImg_info[0];
  103. $this->y = $this->srcImg_info[1]-$this->waterImg_info[1];
  104. break 1;
  105. }
  106. }
  107. private function waterimg() {
  108. if ($this->srcImg_info[0] waterImg_info[0] || $this->srcImg_info[1] waterImg_info[1]){
  109. die('水印比原图大!');
  110. }
  111. $this->waterpos();
  112. $cut = imagecreatetruecolor($this->waterImg_info[0],$this->waterImg_info[1]);
  113. imagecopy($cut,$this->im,0,0,$this->x,$this->y,$this->waterImg_info[0],$this->waterImg_info[1]);
  114. $pct = $this->transparent;
  115. imagecopy($cut,$this->water_im,0,0,0,0,$this->waterImg_info[0],$this->waterImg_info[1]);
  116. imagecopymerge($this->im,$cut,$this->x,$this->y,0,0,$this->waterImg_info[0],$this->waterImg_info[1],$pct);
  117. }
  118. private function waterstr() {
  119. $rect = imagettfbbox($this->fontSize,0,$this->fontFile,$this->waterStr);
  120. $w = abs($rect[2]-$rect[6]);
  121. $h = abs($rect[3]-$rect[7]);
  122. $fontHeight = $this->fontSize;
  123. $this->water_im = imagecreatetruecolor($w, $h);
  124. imagealphablending($this->water_im,false);
  125. imagesavealpha($this->water_im,true);
  126. $white_alpha = imagecolorallocatealpha($this->water_im,255,255,255,127);
  127. imagefill($this->water_im,0,0,$white_alpha);
  128. $color = imagecolorallocate($this->water_im,$this->fontColor[0],$this->fontColor[1],$this->fontColor[2]);
  129. imagettftext($this->water_im,$this->fontSize,0,0,$this->fontSize,$color,$this->fontFile,$this->waterStr);
  130. $this->waterImg_info = array(0=>$w,1=>$h);
  131. $this->waterimg();
  132. }
  133. function output() {
  134. $this->imginfo();
  135. if ($this->waterType == 0) {
  136. $this->waterstr();
  137. }else {
  138. $this->waterimginfo();
  139. $this->waterimg();
  140. }
  141. switch ($this->srcImg_info[2]) {
  142. case 3:
  143. imagepng($this->im,$this->srcImg);
  144. break 1;
  145. case 2:
  146. imagejpeg($this->im,$this->srcImg);
  147. break 1;
  148. case 1:
  149. imagegif($this->im,$this->srcImg);
  150. break 1;
  151. default:
  152. die('添加水印失败!');
  153. break;
  154. }
  155. imagedestroy($this->im);
  156. imagedestroy($this->water_im);
  157. }
  158. }
  159. ?>
复制代码


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

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment