search
HomeBackend DevelopmentPHP TutorialPHP image processing function class (watermark, thumbnail) [About proportional compression and cropping compression]

Below is a simple picture processing class whose functions include: watermark, thumbnail, etc.
However, there are two ways to generate thumbnails: one is to directly compress the image proportionally, and the other is to crop and then compress the image. In my opinion, the difference between equal-case compression and cropping compression is:
Equal example compression: It can ensure that the width and length ratio of the image is reasonable and the image is complete. However, actual size is not guaranteed to meet requirements.
Cropping and compression: It can ensure that the width and length ratio of the picture is reasonable, and the actual size can also be guaranteed. However, the integrity of the picture cannot be guaranteed.image.php
  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 ( 'Failed to load GD library!' );
  21. }
  22. }
  23. /**
  24. *
  25. * Cropping and compression
  26. * @param $src_img image
  27. * @param $save_img generated image
  28. * @param $option parameter options, including: $maxwidth width $maxheight height
  29. * array('width'=> xx,'height'=>xxx)
  30. * @internal
  31. * Our 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 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' => 'The length and width of the original 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. }
  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. // Cropped
  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) image
  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 $ratio = $widthratio;
  143. else
  144. $ratio = $heightratio;
  145. }
  146. if ($resizewidth_tag && ! $resizeheight_tag)
  147. $ratio = $widthratio;
  148. if ($resizeheight_tag && ! $resizewidth_tag)
  149. $ratio = $heightratio;
  150. $newwidth = $src_w * $ratio;
  151. $newheight = $src_h * $ratio;
  152. if (function_exists ( "imagecopyresampled" ))
  153. {
  154. $newim = imagecreatetruecolor ( $newwidth, $newheight );
  155. imagecopyresampled ( $newim, $source, 0, 0, 0, 0, $newwidth, $newheight, $src_w, $src_h );
  156. } else
  157. {
  158. $newim = imagecreate ( $newwidth, $newheight );
  159. imagecopyresized ( $newim, $source, 0, 0, 0, 0, $newwidth, $newheight, $src_w, $src_h );
  160. }
  161. }
  162. //Output (save) picture
  163. if (! empty ( $save_img ))
  164. {
  165. $org_funcs ['save_func'] ( $newim, $save_img );
  166. } else
  167. {
  168. header ( $org_funcs ['header '] );
  169. $org_funcs ['save_func'] ( $newim );
  170. }
  171. imagedestroy ( $newim );
  172. return array ('flag' => True, 'msg' => '' );
  173. }
  174. /**
  175. *
  176. * Generate watermark image
  177. * @param $org_img Original image
  178. * @param $mark_img Watermark image
  179. * @param $save_img When its directory does not exist, it will try to create the directory
  180. * @param array $option is Some basic settings of the watermark include:
  181. * x: the horizontal position of the watermark, the default is the value after subtracting the width of the watermark image
  182. * y: the vertical position of the watermark, the default is the value after subtracting the height of the watermark image
  183. * alpha: alpha Value (control transparency), default is 50
  184. */
  185. public function water_mark($org_img, $mark_img, $save_img = '', $option = array())
  186. {
  187. //Check the picture
  188. $org_ext = $this-> is_img ( $org_img );
  189. if (! $org_ext ['flag'])
  190. {
  191. return $org_ext;
  192. }
  193. $mark_ext = $this->is_img ( $mark_img );
  194. if (! $mark_ext [' flag'])
  195. {
  196. return $mark_ext;
  197. }
  198. //If there is a save path, determine whether the path is correct
  199. if (! empty ( $save_img ))
  200. {
  201. $f = $this->check_dir ( $ save_img );
  202. if (! $f ['flag'])
  203. {
  204. return $f;
  205. }
  206. }
  207. //Get the corresponding canvas
  208. $org_funcs = $this->get_img_funcs ( $org_ext ['msg' ] );
  209. $org_img_im = $org_funcs ['create_func'] ( $org_img );
  210. $mark_funcs = $this->get_img_funcs ( $mark_ext ['msg'] );
  211. $mark_img_im = $mark_funcs ['create_func' ] ( $mark_img );
  212. //Copy watermark image coordinates
  213. $mark_img_im_x = 0;
  214. $mark_img_im_y = 0;
  215. //Copy watermark image height and width
  216. $mark_img_w = ​​imagesx ( $mark_img_im );
  217. $mark_img_h = imagesy ( $mark_img_im );
  218. $org_img_w = ​​imagesx ( $org_img_im );
  219. $org_img_h = imagesx ( $org_img_im );
  220. //Synthetic generated point coordinates
  221. $x = $org_img_w - $mark_img_w;
  222. $org_img_im_x = isset ( $ option ['x'] ) ? $option ['x'] : $x;
  223. $org_img_im_x = ($org_img_im_x > $org_img_w or $org_img_im_x $y = $org_img_h - $mark_img_h;
  224. $org_img_im_y = isset ( $option ['y'] ) ? $option ['y'] : $y;
  225. $org_img_im_y = ($org_img_im_y > $org_img_h or $org_img_im_y
  226. //alpha
  227. $alpha = isset ( $option ['alpha'] ) ? $option ['alpha'] : 50;
  228. $alpha = ($alpha > 100 or $alpha
  229. // Merge picture
  230. Imagecopymerge ($ ORG_IMG_IM, $ Mark_img_im, $ ORG_IMG_I_X, $ ORG_IMG_IM_Y, $ Mark_img_X, $ Mark_img_im_ y, $ mark_img_w, $mark_img_h, $ alpha);
  231. // output (Save) image
  232. if (! empty ( $save_img ))
  233. {
  234. $org_funcs ['save_func'] ( $org_img_im, $save_img );
  235. } else
  236. {
  237. header ( $org_funcs ['header'] );
  238. $org_funcs ['save_func'] ( $org_img_im );
  239. }
  240. // Destroy the canvas
  241. imagedestroy ( $org_img_im );
  242. imagedestroy ( $mark_img_im );
  243. return array ('flag' => True, 'msg' = > '' );
  244. }
  245. /**
  246. *
  247. * Check the image
  248. * @param unknown_type $img_path
  249. * @return array('flag'=>true/false,'msg'=>ext/error message)
  250. */
  251. private function is_img($img_path)
  252. {
  253. if (! file_exists ( $img_path ))
  254. {
  255. return array ('flag' => ; False, 'msg' => "Failed to load image $img_path! " );
  256. }
  257. $ext = explode ( '.', $img_path );
  258. $ext = strtolower ( end ( $ext ) );
  259. if (! in_array ( $ext, $this->exts ))
  260. {
  261. return array ('flag' => False, 'msg' => "The format of the image $img_path is incorrect!" );
  262. }
  263. return array ('flag' => True, 'msg' => $ext );
  264. }
  265. /**
  266. *
  267. * Return the correct image function
  268. * @param unknown_type $ext
  269. */
  270. private function get_img_funcs($ext)
  271. {
  272. //选择
  273. switch ($ext)
  274. {
  275. case 'jpg' :
  276. $header = 'Content-Type:image/jpeg';
  277. $createfunc = 'imagecreatefromjpeg';
  278. $savefunc = 'imagejpeg';
  279. break;
  280. case 'jpeg' :
  281. $header = 'Content-Type:image/jpeg';
  282. $createfunc = 'imagecreatefromjpeg';
  283. $savefunc = 'imagejpeg';
  284. break;
  285. case 'gif' :
  286. $header = 'Content-Type:image/gif';
  287. $createfunc = 'imagecreatefromgif';
  288. $savefunc = 'imagegif';
  289. break;
  290. case 'bmp' :
  291. $header = 'Content-Type:image/bmp';
  292. $createfunc = 'imagecreatefrombmp';
  293. $savefunc = 'imagebmp';
  294. break;
  295. default :
  296. $header = 'Content-Type:image/png';
  297. $createfunc = 'imagecreatefrompng';
  298. $savefunc = 'imagepng';
  299. }
  300. return array ('save_func' => $savefunc, 'create_func' => $createfunc, 'header' => $header );
  301. }
  302. /**
  303. *
  304. * Check and try to create the directory
  305. * @param $save_img
  306. */
  307. private function check_dir($save_img)
  308. {
  309. $dir = dirname ( $save_img );
  310. if (! is_dir ( $dir ))
  311. {
  312. if (! mkdir ( $dir, 0777, true ))
  313. {
  314. return array ('flag' => False, 'msg' => "图片保存目录 $dir 无法创建!" );
  315. }
  316. }
  317. return array ('flag' => True, 'msg' => '' );
  318. }
  319. }
  320. if (! empty ( $_FILES ['test'] ['tmp_name'] ))
  321. {
  322. //例子
  323. $img = new Img ();
  324. //原图
  325. $name = explode ( '.', $_FILES ['test'] ['name'] );
  326. $org_img = 'D:/test.' . end ( $name );
  327. move_uploaded_file ( $_FILES ['test'] ['tmp_name'], $org_img );
  328. $option = array ('width' => $_POST ['width'], 'height' => $_POST ['height'] );
  329. if ($_POST ['type'] == 1)
  330. {
  331. $s = $img->resize_image ( $org_img, '', $option );
  332. } else
  333. {
  334. $img->thumb_img ( $org_img, '', $option );
  335. }
  336. unlink ( $org_img );
  337. }
复制代码

使用方式:

水印
  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 $option = array ('x' => 0, 'y' => 0, 'alpha' => 50 );

2$option = array ('x' => 50, 'y' => 50, 'alpha' => 80 );


3 如果你不设置$option 参数,将会采用默认值:

如果要纯文字式的水印,可以参看这里:http://www.php.net/manual/zh/image.examples.merged-watermark.php
  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. $option = array ('width' => 200, 'height' => 200);
复制代码

水印与压缩图
  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 ); //等比例压缩类似
复制代码

When compressing the generated watermark image, the format of the image generated after compression should be consistent with the original image and watermark image. Otherwise, some unknown errors will occur.

Also note: The image compression principle was not invented by me.
Image processing, proportional, 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 in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools