search
HomeBackend DevelopmentPHP TutorialImage scaling watermark PHP class

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

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 can you check if a PHP session has already started?How can you check if a PHP session has already started?Apr 30, 2025 am 12:20 AM

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Describe a scenario where using sessions is essential in a web application.Describe a scenario where using sessions is essential in a web application.Apr 30, 2025 am 12:16 AM

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

How can you manage concurrent session access in PHP?How can you manage concurrent session access in PHP?Apr 30, 2025 am 12:11 AM

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

What are the limitations of using PHP sessions?What are the limitations of using PHP sessions?Apr 30, 2025 am 12:04 AM

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Explain how load balancing affects session management and how to address it.Explain how load balancing affects session management and how to address it.Apr 29, 2025 am 12:42 AM

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Explain the concept of session locking.Explain the concept of session locking.Apr 29, 2025 am 12:39 AM

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Are there any alternatives to PHP sessions?Are there any alternatives to PHP sessions?Apr 29, 2025 am 12:36 AM

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Define the term 'session hijacking' in the context of PHP.Define the term 'session hijacking' in the context of PHP.Apr 29, 2025 am 12:33 AM

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function