Home Backend Development PHP Tutorial PHP thumbnail and image watermark class (proportional scaling of image size)

PHP thumbnail and image watermark class (proportional scaling of image size)

Jul 25, 2016 am 08:51 AM

  1. /**

  2. *
  3. * Image processing class
  4. * @author FC_LAMP
  5. * @internal functions include: watermark, thumbnail
  6. */
  7. class Img
  8. {
  9. //Image format
  10. private $exts = array ('jpg', 'jpeg', 'gif ', 'bmp', 'png' );

  11. /**

  12. *
  13. *
  14. * @throws Exception
  15. */
  16. public function __construct()
  17. {
  18. if (! function_exists ( 'gd_info' ))
  19. {
  20. throw new Exception ( 'Loading GD library failed!' );
  21. }
  22. }

  23. /**

  24. *
  25. * Cropping and compression
  26. * @param $src_img picture
  27. * @param $save_img generated picture
  28. * @param $option parameter options, including: $maxwidth width $maxheight height
  29. * array('width'=> xx,'height'=>xxx)
  30. * @internal
  31. * General image compression method, when the image is too long or too wide, the generated image
  32. * will be "squashed". For this, crop first and then press Proportional compression method
  33. */
  34. public function thumb_img($src_img, $save_img = '', $option)
  35. {

  36. if (empty ( $option ['width'] ) or empty ( $option ['height'] ))

  37. {
  38. return array ('flag' => False, 'msg' => 'Original The length and width of the image cannot be less than 0' );
  39. }
  40. $org_ext = $this->is_img ( $src_img );
  41. if (! $org_ext ['flag'])
  42. {
  43. return $org_ext;
  44. }< /p>
  45. //If there is a save path, determine whether the path is correct

  46. if (! empty ( $save_img ))
  47. {
  48. $f = $this->check_dir ( $save_img );
  49. if ( ! $f ['flag'])
  50. {
  51. return $f;
  52. }
  53. }

  54. //Get the corresponding method

  55. $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] );

  56. //Get the original size

  57. $source = $org_funcs ['create_func'] ( $src_img );
  58. $src_w = imagesx ( $source );
  59. $ src_h = imagesy ( $source );

  60. //Adjust the original image (keep the original shape of the image and crop the image)

  61. $dst_scale = $option ['height'] / $option ['width'] ; //Target image aspect ratio
  62. $src_scale = $src_h / $src_w; // Original image aspect ratio
  63. if ($src_scale >= $dst_scale)
  64. { // Too high
  65. $w = intval ( $src_w );
  66. $h = intval ( $dst_scale * $w );

  67. $x = 0;

  68. $y = ($src_h - $h) / 3;
  69. } else
  70. { / / Too wide
  71. $h = intval ( $src_h );
  72. $w = intval ( $h / $dst_scale );

  73. $x = ($src_w - $w) / 2;

  74. $y = 0;
  75. }
  76. // Crop
  77. $croped = imagecreatetruecolor ( $w, $h );
  78. imagecopy ( $croped, $source, 0, 0, $x, $y, $src_w, $src_h );
  79. // Scaling
  80. $scale = $option ['width'] / $w;
  81. $target = imagecreatetruecolor ( $option ['width'], $option ['height'] );
  82. $final_w = intval ( $w * $scale );
  83. $final_h = intval ( $h * $scale );
  84. imagecopyresampled ( $target, $croped, 0, 0, 0, 0, $final_w, $final_h, $w, $h );
  85. imagedestroy ( $croped );

  86. //Output (save) picture

  87. if (! empty ( $save_img ))
  88. {

  89. $org_funcs ['save_func' ] ( $target, $save_img );

  90. } else
  91. {
  92. header ( $org_funcs ['header'] );
  93. $org_funcs ['save_func'] ( $target );
  94. }
  95. imagedestroy ( $target );
  96. return array ('flag' => True, 'msg' => '' );
  97. }

  98. /**

  99. *
  100. * Scale image
  101. * @param $src_img Original image
  102. * @param $save_img Where to save
  103. * @param $option Parameter setting array('width'=>xx,'height'=> xxx)
  104. *
  105. */
  106. function resize_image($src_img, $save_img = '', $option)
  107. {
  108. $org_ext = $this->is_img ( $src_img );
  109. if (! $org_ext ['flag'])
  110. {
  111. return $org_ext;
  112. }

  113. //If there is a save path, determine whether the path is correct

  114. if (! empty ( $save_img ))
  115. {
  116. $f = $this->check_dir ( $save_img );
  117. if (! $f [ 'flag'])
  118. {
  119. return $f;
  120. }
  121. }

  122. //Get the corresponding method

  123. $org_funcs = $this->get_img_funcs ( $org_ext ['msg' ] );

  124. //Get the original size

  125. $source = $org_funcs ['create_func'] ( $src_img );
  126. $src_w = imagesx ( $source );
  127. $src_h = imagesy ( $source );

  128. if (($option ['width'] && $src_w > $option ['width']) || ($option ['height'] && $src_h > $option ['height']))

  129. {
  130. if ($option ['width'] && $src_w > $option ['width'])
  131. {
  132. $widthratio = $option ['width'] / $src_w;
  133. $resizewidth_tag = true;
  134. }

  135. if ($option ['height'] && $src_h > $option ['height'])

  136. {
  137. $heightratio = $ option ['height'] / $src_h;
  138. $resizeheight_tag = true;
  139. }

  140. if ($resizewidth_tag && $resizeheight_tag)

  141. {
  142. if ($widthratio < $heightratio)
  143. $ ratio = $widthratio;
  144. else
  145. $ratio = $heightratio;
  146. }

  147. if ($resizewidth_tag && ! $resizeheight_tag)

  148. $ratio = $widthratio;
  149. if ($resizeheight_tag && ! $resizewidth_tag)
  150. $ratio = $heightratio;

  151. $newwidth = $src_w * $ratio;

  152. $newheight = $src_h * $ratio;

  153. if (function_exists ( "imagecopyresampled" ))

  154. {
  155. $newim = imagecreatetruecolor ( $newwidth, $newheight );
  156. imagecopyresampled ( $newim, $source, 0, 0, 0, 0, $newwidth, $newheight, $src_w, $src_h );
  157. } else
  158. {
  159. $newim = imagecreate ( $newwidth, $newheight );
  160. imagecopyresized ( $newim, $source, 0, 0, 0, 0, $newwidth, $newheight, $src_w, $src_h );
  161. }
  162. }
  163. //输出(保存)图片
  164. if (! empty ( $save_img ))
  165. {

  166. $org_funcs ['save_func'] ( $newim, $save_img );

  167. } else
  168. {
  169. header ( $org_funcs ['header'] );
  170. $org_funcs ['save_func'] ( $newim );
  171. }
  172. imagedestroy ( $newim );
  173. return array ('flag' => True, 'msg' => '' );
  174. }

  175. /**

  176. *
  177. * Generate watermark image
  178. * @param $org_img Original image
  179. * @param $mark_img Watermark image
  180. * @param $save_img When its directory does not exist, it will try to create the directory
  181. * @param array $option is Some basic settings of the watermark include:
  182. * x: the horizontal position of the watermark, the default is the value after subtracting the width of the watermark image
  183. * y: the vertical position of the watermark, the default is the value after subtracting the height of the watermark image
  184. * alpha: alpha Value (control transparency), default is 50
  185. */
  186. public function water_mark($org_img, $mark_img, $save_img = '', $option = array())
  187. {
  188. //检查图片
  189. $org_ext = $this->is_img ( $org_img );
  190. if (! $org_ext ['flag'])
  191. {
  192. return $org_ext;
  193. }
  194. $mark_ext = $this->is_img ( $mark_img );
  195. if (! $mark_ext ['flag'])
  196. {
  197. return $mark_ext;
  198. }
  199. //如果有保存路径,则确定路径是否正确
  200. if (! empty ( $save_img ))
  201. {
  202. $f = $this->check_dir ( $save_img );
  203. if (! $f ['flag'])
  204. {
  205. return $f;
  206. }
  207. }

  208. //获取相应画布

  209. $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] );
  210. $org_img_im = $org_funcs ['create_func'] ( $org_img );

  211. $mark_funcs = $this->get_img_funcs ( $mark_ext ['msg'] );

  212. $mark_img_im = $mark_funcs ['create_func'] ( $mark_img );

  213. //拷贝水印图片坐标

  214. $mark_img_im_x = 0;
  215. $mark_img_im_y = 0;
  216. //拷贝水印图片高宽
  217. $mark_img_w = imagesx ( $mark_img_im );
  218. $mark_img_h = imagesy ( $mark_img_im );

  219. $org_img_w = imagesx ( $org_img_im );

  220. $org_img_h = imagesx ( $org_img_im );

  221. //合成生成点坐标

  222. $x = $org_img_w - $mark_img_w;
  223. $org_img_im_x = isset ( $option ['x'] ) ? $option ['x'] : $x;
  224. $org_img_im_x = ($org_img_im_x > $org_img_w or $org_img_im_x < 0) ? $x : $org_img_im_x;
  225. $y = $org_img_h - $mark_img_h;
  226. $org_img_im_y = isset ( $option ['y'] ) ? $option ['y'] : $y;
  227. $org_img_im_y = ($org_img_im_y > $org_img_h or $org_img_im_y < 0) ? $y : $org_img_im_y;

  228. //alpha

  229. $alpha = isset ( $option ['alpha'] ) ? $option ['alpha'] : 50;
  230. $alpha = ($alpha > 100 or $alpha < 0) ? 50 : $alpha;

  231. //合并图片

  232. imagecopymerge ( $org_img_im, $mark_img_im, $org_img_im_x, $org_img_im_y, $mark_img_im_x, $mark_img_im_y, $mark_img_w, $mark_img_h, $alpha );

  233. //输出(保存)图片

  234. if (! empty ( $save_img ))
  235. {

  236. $org_funcs ['save_func'] ( $org_img_im, $save_img );

  237. } else
  238. {
  239. header ( $org_funcs ['header'] );
  240. $org_funcs ['save_func'] ( $org_img_im );
  241. }
  242. //销毁画布
  243. imagedestroy ( $org_img_im );
  244. imagedestroy ( $mark_img_im );
  245. return array ('flag' => True, 'msg' => '' );

  246. }

  247. /**

  248. *
  249. * Check the image
  250. * @param unknown_type $img_path
  251. * @return array('flag'=>true/false,'msg'=>ext/error message)
  252. */
  253. private function is_img($img_path)
  254. {
  255. if (! file_exists ( $img_path ))
  256. {
  257. return array ('flag' => False, 'msg' => "加载图片 $img_path 失败!" );
  258. }
  259. $ext = explode ( '.', $img_path );
  260. $ext = strtolower ( end ( $ext ) );
  261. if (! in_array ( $ext, $this->exts ))
  262. {
  263. return array ('flag' => False, 'msg' => "图片 $img_path 格式不正确!" );
  264. }
  265. return array ('flag' => True, 'msg' => $ext );
  266. }

  267. /**

  268. *
  269. * Return the correct image function
  270. * @param unknown_type $ext
  271. */
  272. private function get_img_funcs($ext)
  273. {
  274. //选择
  275. switch ($ext)
  276. {
  277. case 'jpg' :
  278. $header = 'Content-Type:image/jpeg';
  279. $createfunc = 'imagecreatefromjpeg';
  280. $savefunc = 'imagejpeg';
  281. break;
  282. case 'jpeg' :
  283. $header = 'Content-Type:image/jpeg';
  284. $createfunc = 'imagecreatefromjpeg';
  285. $savefunc = 'imagejpeg';
  286. break;
  287. case 'gif' :
  288. $header = 'Content-Type:image/gif';
  289. $createfunc = 'imagecreatefromgif';
  290. $savefunc = 'imagegif';
  291. break;
  292. case 'bmp' :
  293. $header = 'Content-Type:image/bmp';
  294. $createfunc = 'imagecreatefrombmp';
  295. $savefunc = 'imagebmp';
  296. break;
  297. default :
  298. $header = 'Content-Type:image/png';
  299. $createfunc = 'imagecreatefrompng';
  300. $savefunc = 'imagepng';
  301. }
  302. return array ('save_func' => $savefunc, 'create_func' => $createfunc, 'header' => $header );
  303. }

  304. /**

  305. *
  306. * Check and try to create the directory
  307. * @param $save_img
  308. */
  309. private function check_dir($save_img)
  310. {
  311. $dir = dirname ( $save_img );
  312. if (! is_dir ( $dir ))
  313. {
  314. if (! mkdir ( $dir, 0777, true ))
  315. {
  316. return array ('flag' => False, 'msg' => "图片保存目录 $dir 无法创建!" );
  317. }
  318. }
  319. return array ('flag' => True, 'msg' => '' );
  320. }
  321. }

  322. if (! empty ( $_FILES ['test'] ['tmp_name'] ))

  323. {
  324. //例子
  325. $img = new Img ();
  326. //原图
  327. $name = explode ( '.', $_FILES ['test'] ['name'] );
  328. $org_img = 'D:/test.' . end ( $name );
  329. move_uploaded_file ( $_FILES ['test'] ['tmp_name'], $org_img );
  330. $option = array ('width' => $_POST ['width'], 'height' => $_POST ['height'] );
  331. if ($_POST ['type'] == 1)
  332. {
  333. $s = $img->resize_image ( $org_img, '', $option );
  334. } else
  335. {
  336. $img->thumb_img ( $org_img, '', $option );
  337. }
  338. unlink ( $org_img );
  339. }

复制代码

使用方式: php水印

  1. $img = new Img ();
  2. $org_img = 'D:/tt.png';
  3. $mark_img = 'D:/t.png';
  4. //保存水印图片(如果$save_img为空时,将会直接输出图片)
  5. $save_img = 'D:/test99h/testone/sss.png';
  6. //水印设置调节
  7. $option = array ('x' => 50, 'y' => 50, 'alpha' => 80 );
  8. //生成水印图片
  9. $flag = $img->water_mark ( $org_img, $mark_img, $save_img, $option );
复制代码

当调节 $option 参数时,会有相应变化:

  1. //例子

  2. $img = new Img ();
  3. $org_img = 'D:/tt.png';
  4. //压缩图片(100*100)
  5. $option = array ('width' => 100, 'height' => 100 );

  6. //$save_img为空时,将会直接输出图像到浏览器

  7. $save_img = 'D:/test99h/testone/sss_thumb.png';

  8. $flag = $img->thumb_img ( $org_img, $save_img, $option );
复制代码

调节$option的大小值:

  1. $img = new Img ();
  2. //原图
  3. $org_img = 'D:/tt.png';
  4. //水印标记图
  5. $mark_img = 'D:/t.png';
  6. //保存水印图片
  7. $save_img = 'D:/test99h/testone/sss.png';
  8. //水印设置调节
  9. $option = array ('x' => 50, 'y' => 50, 'alpha' => 60 );
  10. //生成水印图片
  11. $flag = $img->water_mark ( $org_img, $mark_img, $save_img, $option );
  12. //压缩水印图片
  13. $option = array ('width' => 200, 'height' => 200 );
  14. //保存压缩图
  15. $save_img2 = 'D:/test99h/testone/sss2_thumb.png';
  16. $flag = $img->thumb_img ( $save_img, $save_img2, $option ); //等比例压缩类似
复制代码

在压缩生成的水印图像时,压缩后生成的图像格式应与原图像,水印图像一致。 不然,会出现一些未知错误。



Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles