PHP image processing function class (watermark image, thumbnail) [about proportional compression and cropping compression]

Source: Internet
Author: User
Tags imagejpeg
PHP image processing function class (watermark image, thumbnail) [about proportional compression and cropping compression]
The following is a simple image processing class, including watermarks and thumbnails.
However, there are two ways to generate a thumbnail: one is to compress the image in proportion, and the other is to crop and then compress the image. In my opinion, the difference between compression and cropping is:
Compression: ensures a reasonable proportion of the image width and length, and the image integrity. But the actual size is not guaranteed to meet the requirements.
Cropping and compression: This ensures a reasonable proportion of the image width and length, and the actual size. However, the image integrity cannot be guaranteed. Image. php

  1. /**
  2. *
  3. * Image processing
  4. * @ Author FC_LAMP
  5. * @ Internal: watermarks and thumbnails
  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 the GD library! ');
  21. }
  22. }
  23. /**
  24. *
  25. * Cropping and compression
  26. * @ Param $ src_img image
  27. * @ Param $ save_img: image generated
  28. * @ Param $ option parameter options, including: $ maxwidth width $ maxheight height
  29. * Array ('width' => xx, 'height' => xxx)
  30. * @ Internal
  31. * Our general method of compressing images is to generate images that are too long or too wide.
  32. * The image will be squashed. for this case, we should first crop the image and then compress it proportionally.
  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 '=> 'Source Image length and width 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 a storage path exists, check 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. // Obtain the corresponding method
  55. $ Org_funcs = $ this-> get_img_funcs ($ org_ext ['MSG ']);
  56. // Obtain 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 (retain the original image shape and crop the image)
  61. $ Dst_scale = $ option ['height']/$ option ['width']; // aspect ratio of the target image
  62. $ Src_scale = $ src_h/$ src_w; // aspect ratio of the source image
  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. // Zoom
  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) the 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. * Proportional scaling image
  101. * @ Param $ src_img original image
  102. * @ Param $ save_img
  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 a storage path exists, check 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. // Obtain the corresponding method
  123. $ Org_funcs = $ this-> get_img_funcs ($ org_ext ['MSG ']);
  124. // Obtain 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, $ 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. // Output (save) the image
  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 a watermark image
  178. * @ Param $ org_img original image
  179. * @ Param $ mark_img watermark marks the image
  180. * @ Param $ save_img tries to create a directory when its directory does not exist.
  181. * @ Param array $ option basic settings for watermarks include:
  182. * X: the horizontal position of the watermark. the default value is the value after the watermark width is subtracted.
  183. * Y: vertical position of the watermark. the default value is the value after the watermark height is subtracted.
  184. * Alpha: alpha value (transparency control). The default value is 50.
  185. */
  186. Public function water_mark ($ org_img, $ mark_img, $ save_img = '', $ option = array ())
  187. {
  188. // Check the image
  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. // If a storage path exists, check whether the path is correct.
  200. If (! Empty ($ save_img ))
  201. {
  202. $ F = $ this-> check_dir ($ save_img );
  203. If (! $ F ['flag'])
  204. {
  205. Return $ f;
  206. }
  207. }
  208. // Obtain the canvas
  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. // Copy the watermark image coordinates
  214. $ Mark_img_im_x = 0;
  215. $ Mark_img_im_y = 0;
  216. // Copy the watermark image height and width
  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. // Combine and generate coordinate points
  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. // Merge images
  232. Imagecopymerge ($ org_img_im, $ mark_img_im, $ org_img_im_x, $ tags, $ mark_img_im_x, $ mark_img_im_y, $ mark_img_w, $ mark_img_h, $ alpha );
  233. // Output (save) the image
  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. // Destroy the canvas
  243. Imagedestroy ($ org_img_im );
  244. Imagedestroy ($ mark_img_im );
  245. Return array ('flag' => True, 'MSG '=> '');
  246. }
  247. /**
  248. *
  249. * Check images
  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 '=> "loading image $ img_path failed! ");
  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 '=> "The image $ img_path format is incorrect! ");
  264. }
  265. Return array ('flag' => True, 'MSG '=> $ ext );
  266. }
  267. /**
  268. *
  269. * Returns the correct image function.
  270. * @ Param unknown_type $ ext
  271. */
  272. Private function get_img_funcs ($ ext)
  273. {
  274. // Select
  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 a 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 '=> "The image storage directory $ dir cannot be created! ");
  317. }
  318. }
  319. Return array ('flag' => True, 'MSG '=> '');
  320. }
  321. }
  322. If (! Empty ($ _ FILES ['test'] ['tmp _ name'])
  323. {
  324. // Example
  325. $ Img = new Img ();
  326. // Source image
  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. }


Usage:

Watermark

  1. $ Img = new Img ();
  2. $ Org_img = 'd:/tt.png ';
  3. $ Mark_img = 'd:/t.png ';
  4. // Save the watermark image (if $ save_img is empty, the image will be output directly)
  5. $ Save_img = 'd:/test99h/testone/sss.png ';
  6. // Adjust watermark settings
  7. $ Option = array ('x' => 50, 'y' => 50, 'alpha' => 80 );
  8. // Generate a watermark image
  9. $ Flag = $ img-> water_mark ($ org_img, $ mark_img, $ save_img, $ option );


When we adjust the $ option parameter, the following changes occur:

1 $ option = array ('x' => 0, 'y' => 0, 'alpha' => 50 );

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


3. if you do not set the $ option parameter, the default value is used:

For plain text watermark, see here: http://www.php.net/manual/zh/image.examples.merged-watermark.php

  1. // Example
  2. $ Img = new Img ();
  3. $ Org_img = 'd:/tt.png ';
  4. // Compress the image (100*100)
  5. $ Option = array ('width' => 100, 'height' => 100 );
  6. // When $ save_img is empty, the image is directly output to the browser.
  7. $ Save_img = 'd:/test99h/testone/sss_thumb.png ';
  8. $ Flag = $ img-> thumb_img ($ org_img, $ save_img, $ option );


Adjust the value of $ option:

  1. $ Option = array ('width' => 200, 'height' => 200 );


Watermarks and compression graphs

  1. $ Img = new Img ();
  2. // Source image
  3. $ Org_img = 'd:/tt.png ';
  4. // Watermark markup image
  5. $ Mark_img = 'd:/t.png ';
  6. // Save the watermark image
  7. $ Save_img = 'd:/test99h/testone/sss.png ';
  8. // Adjust watermark settings
  9. $ Option = array ('x' => 50, 'y' => 50, 'alpha' => 60 );
  10. // Generate a watermark image
  11. $ Flag = $ img-> water_mark ($ org_img, $ mark_img, $ save_img, $ option );
  12. // Compress the watermark image
  13. $ Option = array ('width' => 200, 'height' => 200 );
  14. // Save the compression graph
  15. $ Save_img2 = 'd:/test99h/testone/sss2_thumb.png ';
  16. $ Flag = $ img-> thumb_img ($ save_img, $ save_img2, $ option); // proportional compression is similar


When compressing the generated watermark image, the format of the compressed image should be consistent with that of the original image and the watermark image. Otherwise, some unknown errors may occur.

Note: the image compression principle is not created by myself.

Image Processing, proportional, PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.