PHP Image Processing function class (watermark, thumbnail) [about equal scale compression and clipping compression]

Source: Internet
Author: User
Tags imagejpeg
The following simple to write a picture processing class, features include: watermarks, thumbnails and so on.
However, there are two ways to generate thumbnails: one is to compress the pictures directly proportionally, and the other is to cut and then compress the images first. In my opinion, the difference between compression and cropping compression is:
and other examples of compression: to ensure that the picture of the width and length of reasonable, and the picture has integrity. However, the actual size is not guaranteed to meet the requirements.
Clip compression: To ensure that the picture of the width and length of reasonable, the actual size can also be guaranteed. But picture integrity is not guaranteed. image.php
  1. /**
  2. *
  3. * Image Processing Class
  4. * @author Fc_lamp
  5. * @internal features include: watermark, thumbnail
  6. */
  7. Class IMG
  8. {
  9. Picture 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 (' Load GD library failed! ' );
  21. }
  22. }
  23. /**
  24. *
  25. * Clipping compression
  26. * @param $src _img Pictures
  27. * @param $save _img After the image is created
  28. * @param $option parameter options, including: $maxwidth wide $maxheight High
  29. * Array (' width ' =>xx, ' height ' =>xxx)
  30. * @internal
  31. * Our general compressed image method, the image generated when the picture is too long or too wide
  32. * Will be "squashed", for this should be the first cut after the 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 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 there is a save path, determine if 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 appropriate 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 picture in the original shape to crop the image)
  61. $DST _scale = $option [' height ']/$option [' width ']; Target image aspect ratio
  62. $src _scale = $src _h/$src _w; Original 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. {//Over width
  71. $h = Intval ($src _h);
  72. $w = Intval ($h/$DST _scale);
  73. $x = ($src _w-$w)/2;
  74. $y = 0;
  75. }
  76. Cutting
  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. * Equal scaled image
  101. * @param $src _img original picture
  102. * @param where $save _img need to be saved
  103. * @param $option parameter Set 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 if 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 appropriate 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. Output (Save) picture
  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. * Watermark Image generation
  178. * @param $org _img Original image
  179. * @param $mark _img watermark Tagged Image
  180. * @param $save _img When its directory does not exist, try to create a directory
  181. * @param array $option Some basic settings for watermarks include:
  182. * x: The horizontal position of the watermark, which defaults to the value after subtracting the width of the watermark map
  183. * Y: The vertical position of the watermark, which defaults to the value after subtracting the height of the watermark map
  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. Check the picture
  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 there is a save path, determine if 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. Get the appropriate 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 watermark Picture coordinates
  214. $mark _img_im_x = 0;
  215. $mark _img_im_y = 0;
  216. High-width copy watermark image
  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. Synthesis generating Point coordinates
  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 > or $alpha < 0)? : $alpha;
  231. Merging pictures
  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. Output (Save) picture
  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. Destroying the canvas
  243. Imagedestroy ($org _img_im);
  244. Imagedestroy ($mark _img_im);
  245. Return Array (' flag ' = = True, ' msg ' = = ');
  246. }
  247. /**
  248. *
  249. * Check Pictures
  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 ' = ' = ' Load picture $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 ' = ' = ' picture $img _path format is incorrect! " );
  264. }
  265. Return Array (' flag ' = = True, ' msg ' = $ext);
  266. }
  267. /**
  268. *
  269. * Returns the correct picture function
  270. * @param unknown_type $ext
  271. */
  272. Private Function Get_img_funcs ($ext)
  273. {
  274. Choose
  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 ' = ' = ' picture saved 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. Original
  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. }
Copy Code
How to use:

Watermarking
    1. $img = new img ();
    2. $org _img = ' d:/tt.png ';
    3. $mark _img = ' d:/t.png ';
    4. Save the watermark picture (if $save_img is empty, the image will be output directly)
    5. $save _img = ' d:/test99h/testone/sss.png ';
    6. Watermark Setting Adjustment
    7. $option = Array (' x ' = +, ' y ' = +, ' alpha ' = 80);
    8. Create a watermark Picture
    9. $flag = $img->water_mark ($org _img, $mark _img, $save _img, $option);
Copy Code
When we adjust the $option parameters, there is a corresponding change:

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

2$option = Array (' x ' = +, ' y ' = +, ' alpha ' = 80);


3 If you do not set the $option parameter, the default value will be used:

If you want a text-only watermark, you can 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 picture (100*100)
    5. $option = Array (' width ' = +, ' height ' = 100);
    6. When the $save _img is empty, the image will be output directly to the browser
    7. $save _img = ' d:/test99h/testone/sss_thumb.png ';
    8. $flag = $img->thumb_img ($org _img, $save _img, $option);
Copy Code
Adjust the size value of the $option:
    1. $option = Array (' width ' = =, ' height ' = 200);
Copy Code
Watermark and compression diagram
    1. $img = new img ();
    2. Original
    3. $org _img = ' d:/tt.png ';
    4. Watermark Marker Diagram
    5. $mark _img = ' d:/t.png ';
    6. Save watermark Picture
    7. $save _img = ' d:/test99h/testone/sss.png ';
    8. Watermark Setting Adjustment
    9. $option = Array (' x ' = +, ' y ' = +, ' alpha ' = 60);
    10. Create a watermark Picture
    11. $flag = $img->water_mark ($org _img, $mark _img, $save _img, $option);
    12. Compress watermark Picture
    13. $option = Array (' width ' = =, ' height ' = 200);
    14. Save a compressed diagram
    15. $save _img2 = ' d:/test99h/testone/sss2_thumb.png ';
    16. $flag = $img->thumb_img ($save _img, $save _img2, $option); Equal proportional compression Similar
Copy Code
When compressing the generated watermark image, the image format generated after compression should be consistent with the original image and watermark image. Otherwise, there are some unknown errors.

Another note: Picture compression principle is not my own creation.
Image processing, equal proportions, 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.