search
HomeBackend DevelopmentPHP TutorialPHP class to add watermark to images

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

PHP


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
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

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 Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.