search
HomeBackend DevelopmentPHP TutorialPHP class that implements thumbnails and watermarks

  1. /**
  2. * Image scaling watermark class
  3. *
  4. * @version 1.0;
  5. *
  6. */
  7. class cls_photo
  8. {
  9. protected $waterrate = 0.2; //The ratio of the watermark icon on the image
  10. protected $width = 300; //The default width of the thumbnail
  11. protected $height = 200; //Default height of thumbnail
  12. protected $padding = 5; //Distance from watermark image to edge
  13. protected $water_mark = "./water.png";
  14. protected $water_mark_pos = 5; //Watermark image position ( 1=upper left corner, 2=upper right corner, 3=lower left corner, 4=lower right corner, 5 center)
  15. protected $watermode = 0; // 0 does not print watermark when thumbnail 1 prints watermark when thumbnail
  16. protected $magick_handle; //Picture operation handle
  17. protected $format = array('jpg','gif','png','jpeg'); // Picture file format limitation
  18. protected $smallpic_mode = 2; //Default mode 0 is not generated Thumbnail, 1 is crop scaling, 2 is proportional scaling, 3 is scaling fill mode
  19. /**
  20. * Set image parameters
  21. *
  22. * @param $arg Image parameters can be put into the array multiple times as follows
  23. * @param $protected parameter value
  24. * array(
  25. * 'waterrate'=>0.2,
  26. * 'water_mark '=>'./water.png',
  27. * 'water_mark_pos'=>4,
  28. * 'smallpic_mode'=>1
  29. * );
  30. * @return ture/false
  31. */
  32. public function set_args($arg,$val="")
  33. {
  34. $params = array( 'waterrate','water_mark','water_mark_pos','smallpic_mode','watermode','width','height');
  35. if(is_array($arg))
  36. {
  37. foreach ($arg as $k => ;$v)
  38. {
  39. if(in_array($k,$params))
  40. {
  41. $this->$k = $v;
  42. }
  43. }
  44. }
  45. else
  46. {
  47. if(empty($val) )
  48. {
  49. return false;
  50. }
  51. else
  52. {
  53. if(in_array($arg,$params))
  54. {
  55. $this->$arg = $val;
  56. }
  57. }
  58. }
  59. return true;
  60. }
  61. /**
  62. * Image scaling
  63. *
  64. * @param $src_file source file path
  65. * @param $dst_file destination file path
  66. * @return thumbnail image path/false
  67. */
  68. public function scale($src_file,$dst_file="")
  69. {
  70. $dst_width = $this->width;
  71. $dst_height = $this->height;
  72. $mode = $this->smallpic_mode;
  73. $magic_water_handle = NewMagickWand();
  74. if (!MagickReadImage($magic_water_handle, $src_file))return false;
  75. //Type
  76. $srcext = strtolower(MagicGetImageFormat($magic_water_handle) );
  77. if($srcext=='bmp')
  78. {
  79. $srcext = 'jpeg';
  80. }
  81. if(!in_array($srcext,$this->format))return false;
  82. //size
  83. $src_width = MagickGetImageWidth($magic_water_handle);
  84. $src_height = MagickGetImageHeight($magic_water_handle);
  85. //Crop scaling mode
  86. if($mode == 1)
  87. {
  88. $pos_x=$pos_y = 0;//Crop Cut temporary position
  89. $src_widthc = $src_width;//Cut temporary width
  90. $src_heightc = $src_height;//Cut temporary height
  91. if($src_width/$src_height>$dst_width/$dst_height)
  92. {
  93. $src_widthc = $ SRC_HEIGHT*$ dst_width/$ dst_height;
  94. $ POS_X = ($ src_width-$ src_widthc)/2; dst_height/$ dst_width;
  95. $ POS_Y = ($ SRC_HEIGHT -$src_heightc)/2;
  96. }
  97. MagickCropImage($magic_water_handle,$src_widthc,$src_heightc,$pos_x,$pos_y);//Crop
  98. //Because after the MagickCropImage function, the Gif image changes, but the canvas remains unchanged
  99. $ this->magick_handle = NewMagickWand();
  100. MagickNewImage($this->magick_handle,$src_widthc,$src_heightc,'#ffffff');
  101. MagickSetFormat($this->magick_handle,$srcext);
  102. MagickCompositeImage($ this->magick_handle,$magic_water_handle,MW_OverCompositeOp,0,0);
  103. //Scale
  104. MagickScaleImage($this->magick_handle, $dst_width, $dst_height);
  105. }
  106. //Proportional scaling mode
  107. if($ mode == 2)
  108. {
  109. if($src_width/$src_height>$dst_width/$dst_height)
  110. {
  111. $dst_height=$dst_width*$src_height/$src_width;
  112. }
  113. else
  114. {
  115. $dst_width=$dst_height * $src_width/$src_height;
  116. }
  117. $this->magick_handle=$magic_water_handle;//替换
  118. MagickScaleImage($this->magick_handle, $dst_width, $dst_height);//缩放
  119. }
  120. //缩放填充模式
  121. if($mode == 3)
  122. {
  123. if($src_width/$src_height>$dst_width/$dst_height)
  124. {
  125. $dst_heightc=$dst_width*$src_height/$src_width;
  126. $dst_widthc=$dst_width;
  127. }
  128. else
  129. {
  130. $dst_widthc=$dst_height*$src_width/$src_height;
  131. $dst_heightc=$dst_height;
  132. }
  133. MagickScaleImage($magic_water_handle, $dst_widthc, $dst_heightc);//缩放
  134. $this->magick_handle = NewMagickWand();
  135. MagickNewImage($this->magick_handle,$dst_width,$dst_height,$this->smallpic_bgcolor);
  136. MagickSetFormat($this->magick_handle,$srcext);
  137. MagickCompositeImage($this->magick_handle,$magic_water_handle,MW_OverCompositeOp,($dst_width-$dst_widthc)/2,($dst_height-$dst_heightc)/2);
  138. }
  139. //打水印
  140. if($this->watermode == 1)
  141. {
  142. $this->set_mark();
  143. }
  144. if(empty($dst_file))
  145. {
  146. //建立临时文件
  147. $dst_file = tempnam($_SERVER["SINASRV_CACHE_DIR"],"TMP_IMG");
  148. }
  149. MagickWriteImage($this->magick_handle, $dst_file);
  150. return $dst_file;
  151. }
  152. /**
  153. * Watermarking
  154. *
  155. * @param $src_file The path of the image to be watermarked
  156. * @param $dst_file The file saving path for producing watermarks. If it is empty, a random temporary file will be produced
  157. * @return The path of the watermark file/false
  158. */
  159. public function water_mark($src_file,$dst_file="")
  160. {
  161. $this->magick_handle = NewMagickWand();
  162. if (!MagickReadImage($this->magick_handle, $src_file))
  163. return false;
  164. $this->set_mark();
  165. if(empty($dst_file))
  166. {
  167. //建立临时文件
  168. $dst_file = tempnam($_SERVER["SINASRV_CACHE_DIR"],"TMP_IMG");
  169. }
  170. MagickWriteImage($this->magick_handle, $dst_file);
  171. return $dst_file;
  172. }
  173. /**
  174. * Internal interface
  175. * Watermark pictures
  176. *
  177. */
  178. protected function set_mark()
  179. {
  180. //尺寸
  181. $dst_width = MagickGetImageWidth($this->magick_handle);
  182. $dst_height = MagickGetImageHeight($this->magick_handle);
  183. //处理水印图
  184. if ($this->water_mark && is_file($this->water_mark))
  185. {
  186. $magic_water_handle = NewMagickWand();
  187. MagickRemoveImage($magic_water_handle);
  188. if (MagickReadImage($magic_water_handle, $this->water_mark))
  189. {
  190. MagickScaleImage($magic_water_handle, $dst_width*$this->waterrate, $dst_width*$this->waterrate*MagickGetImageHeight($magic_water_handle)/MagickGetImageWidth($magic_water_handle));//缩放水印到图片的1/5
  191. if ($this->water_mark_pos == 1)
  192. {
  193. $left = $this->padding;
  194. $top = $this->padding;
  195. }
  196. elseif ($this->water_mark_pos == 2)
  197. {
  198. $left = $dst_width-$this->padding-MagickGetImageWidth($magic_water_handle);
  199. $top = $this->padding;
  200. }
  201. elseif ($this->water_mark_pos == 3)
  202. {
  203. $left = $this->padding;
  204. $top = $dst_height -$this->padding-MagickGetImageHeight($magic_water_handle);
  205. }
  206. elseif ($this->water_mark_pos == 4)
  207. {
  208. $left = $dst_width-$this->padding-MagickGetImageWidth($magic_water_handle);
  209. $top =$dst_height -$this->padding-MagickGetImageHeight($magic_water_handle);
  210. }
  211. elseif ($this->water_mark_pos == 5)
  212. {
  213. $left = ($dst_width-MagickGetImageWidth($magic_water_handle))/2;
  214. $top =($dst_height -MagickGetImageHeight($magic_water_handle))/2;
  215. }
  216. MagickCompositeImage($this->magick_handle,$magic_water_handle,MW_OverCompositeOp,$left,$top);
  217. }
  218. }
  219. }
  220. }
复制代码

Waka, 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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

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

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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