Maison développement back-end tutoriel php PHP图片处理函数 类 (水印图,缩略图)[关于等比例压缩与裁剪压缩]

PHP图片处理函数 类 (水印图,缩略图)[关于等比例压缩与裁剪压缩]

Jul 25, 2016 am 08:44 AM

下面简单的写了一个图片处理类,功能包括:水印,缩略图等。
不过,对于生成缩略图有两种方式:一种是直接按比例来压缩图片,另外一种是先裁剪再压缩的方式。在自己看来等例压缩与裁剪压缩区别就在于:
等例压缩:能保证图片的宽长比例合理,且图片有完整性。但实际大小不保证符合要求。
裁剪压缩: 能保证图片的宽长比例合理,实际大小也能保证。但图片完整性不能保证。 image.php
  1. /**
  2. *
  3. * 图像处理类
  4. * @author FC_LAMP
  5. * @internal功能包含:水印,缩略图
  6. */
  7. class Img
  8. {
  9. //图片格式
  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 ( '加载GD库失败!' );
  21. }
  22. }
  23. /**
  24. *
  25. * 裁剪压缩
  26. * @param $src_img 图片
  27. * @param $save_img 生成后的图片
  28. * @param $option 参数选项,包括: $maxwidth 宽 $maxheight 高
  29. * array('width'=>xx,'height'=>xxx)
  30. * @internal
  31. * 我们一般的压缩图片方法,在图片过长或过宽时生成的图片
  32. * 都会被“压扁”,针对这个应采用先裁剪后按比例压缩的方法
  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' => '原图长度与宽度不能小于0' );
  39. }
  40. $org_ext = $this->is_img ( $src_img );
  41. if (! $org_ext ['flag'])
  42. {
  43. return $org_ext;
  44. }
  45. //如果有保存路径,则确定路径是否正确
  46. if (! empty ( $save_img ))
  47. {
  48. $f = $this->check_dir ( $save_img );
  49. if (! $f ['flag'])
  50. {
  51. return $f;
  52. }
  53. }
  54. //获取出相应的方法
  55. $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] );
  56. //获取原大小
  57. $source = $org_funcs ['create_func'] ( $src_img );
  58. $src_w = imagesx ( $source );
  59. $src_h = imagesy ( $source );
  60. //调整原始图像(保持图片原形状裁剪图像)
  61. $dst_scale = $option ['height'] / $option ['width']; //目标图像长宽比
  62. $src_scale = $src_h / $src_w; // 原图长宽比
  63. if ($src_scale >= $dst_scale)
  64. { // 过高
  65. $w = intval ( $src_w );
  66. $h = intval ( $dst_scale * $w );
  67. $x = 0;
  68. $y = ($src_h - $h) / 3;
  69. } else
  70. { // 过宽
  71. $h = intval ( $src_h );
  72. $w = intval ( $h / $dst_scale );
  73. $x = ($src_w - $w) / 2;
  74. $y = 0;
  75. }
  76. // 剪裁
  77. $croped = imagecreatetruecolor ( $w, $h );
  78. imagecopy ( $croped, $source, 0, 0, $x, $y, $src_w, $src_h );
  79. // 缩放
  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. //输出(保存)图片
  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. * 等比例缩放图像
  101. * @param $src_img 原图片
  102. * @param $save_img 需要保存的地方
  103. * @param $option 参数设置 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. //如果有保存路径,则确定路径是否正确
  114. if (! empty ( $save_img ))
  115. {
  116. $f = $this->check_dir ( $save_img );
  117. if (! $f ['flag'])
  118. {
  119. return $f;
  120. }
  121. }
  122. //获取出相应的方法
  123. $org_funcs = $this->get_img_funcs ( $org_ext ['msg'] );
  124. //获取原大小
  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. //输出(保存)图片
  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. * 生成水印图片
  177. * @param $org_img 原图像
  178. * @param $mark_img 水印标记图像
  179. * @param $save_img 当其目录不存在时,会试着创建目录
  180. * @param array $option 为水印的一些基本设置包含:
  181. * x:水印的水平位置,默认为减去水印图宽度后的值
  182. * y:水印的垂直位置,默认为减去水印图高度后的值
  183. * alpha:alpha值(控制透明度),默认为50
  184. */
  185. public function water_mark($org_img, $mark_img, $save_img = '', $option = array())
  186. {
  187. //检查图片
  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. //如果有保存路径,则确定路径是否正确
  199. if (! empty ( $save_img ))
  200. {
  201. $f = $this->check_dir ( $save_img );
  202. if (! $f ['flag'])
  203. {
  204. return $f;
  205. }
  206. }
  207. //获取相应画布
  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. //拷贝水印图片坐标
  213. $mark_img_im_x = 0;
  214. $mark_img_im_y = 0;
  215. //拷贝水印图片高宽
  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. //合成生成点坐标
  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. //合并图片
  230. 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 );
  231. //输出(保存)图片
  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. //销毁画布
  241. imagedestroy ( $org_img_im );
  242. imagedestroy ( $mark_img_im );
  243. return array ('flag' => True, 'msg' => '' );
  244. }
  245. /**
  246. *
  247. * 检查图片
  248. * @param unknown_type $img_path
  249. * @return array('flag'=>true/false,'msg'=>ext/错误信息)
  250. */
  251. private function is_img($img_path)
  252. {
  253. if (! file_exists ( $img_path ))
  254. {
  255. return array ('flag' => False, 'msg' => "加载图片 $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' => "图片 $img_path 格式不正确!" );
  262. }
  263. return array ('flag' => True, 'msg' => $ext );
  264. }
  265. /**
  266. *
  267. * 返回正确的图片函数
  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. * 检查并试着创建目录
  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 ); //等比例压缩类似
复制代码

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

另注:图片压缩原理非本人所创。
图片处理, 等比例, PHP


Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn

Outils d'IA chauds

Undresser.AI Undress

Undresser.AI Undress

Application basée sur l'IA pour créer des photos de nu réalistes

AI Clothes Remover

AI Clothes Remover

Outil d'IA en ligne pour supprimer les vêtements des photos.

Undress AI Tool

Undress AI Tool

Images de déshabillage gratuites

Clothoff.io

Clothoff.io

Dissolvant de vêtements AI

AI Hentai Generator

AI Hentai Generator

Générez AI Hentai gratuitement.

Article chaud

R.E.P.O. Crystals d'énergie expliqués et ce qu'ils font (cristal jaune)
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Meilleurs paramètres graphiques
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Comment réparer l'audio si vous n'entendez personne
3 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: Comment déverrouiller tout dans Myrise
4 Il y a quelques semaines By 尊渡假赌尊渡假赌尊渡假赌

Outils chauds

Bloc-notes++7.3.1

Bloc-notes++7.3.1

Éditeur de code facile à utiliser et gratuit

SublimeText3 version chinoise

SublimeText3 version chinoise

Version chinoise, très simple à utiliser

Envoyer Studio 13.0.1

Envoyer Studio 13.0.1

Puissant environnement de développement intégré PHP

Dreamweaver CS6

Dreamweaver CS6

Outils de développement Web visuel

SublimeText3 version Mac

SublimeText3 version Mac

Logiciel d'édition de code au niveau de Dieu (SublimeText3)

Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Curl dans PHP: Comment utiliser l'extension PHP Curl dans les API REST Mar 14, 2025 am 11:42 AM

L'extension PHP Client URL (CURL) est un outil puissant pour les développeurs, permettant une interaction transparente avec des serveurs distants et des API REST. En tirant parti de Libcurl, une bibliothèque de transfert de fichiers multi-protocol très respectée, PHP Curl facilite Efficient Execu

Expliquez le concept de liaison statique tardive en PHP. Expliquez le concept de liaison statique tardive en PHP. Mar 21, 2025 pm 01:33 PM

L'article traite de la liaison statique tardive (LSB) dans PHP, introduite dans PHP 5.3, permettant une résolution d'exécution de la méthode statique nécessite un héritage plus flexible. Problème main: LSB vs polymorphisme traditionnel; Applications pratiques de LSB et perfo potentiel

Expliquez les jetons Web JSON (JWT) et leur cas d'utilisation dans les API PHP. Expliquez les jetons Web JSON (JWT) et leur cas d'utilisation dans les API PHP. Apr 05, 2025 am 12:04 AM

JWT est une norme ouverte basée sur JSON, utilisée pour transmettre en toute sécurité des informations entre les parties, principalement pour l'authentification de l'identité et l'échange d'informations. 1. JWT se compose de trois parties: en-tête, charge utile et signature. 2. Le principe de travail de JWT comprend trois étapes: la génération de JWT, la vérification de la charge utile JWT et l'analyse. 3. Lorsque vous utilisez JWT pour l'authentification en PHP, JWT peut être généré et vérifié, et les informations sur le rôle et l'autorisation des utilisateurs peuvent être incluses dans l'utilisation avancée. 4. Les erreurs courantes incluent une défaillance de vérification de signature, l'expiration des jetons et la charge utile surdimensionnée. Les compétences de débogage incluent l'utilisation des outils de débogage et de l'exploitation forestière. 5. L'optimisation des performances et les meilleures pratiques incluent l'utilisation des algorithmes de signature appropriés, la définition des périodes de validité raisonnablement,

Caractéristiques de sécurité du cadre: protection contre les vulnérabilités. Caractéristiques de sécurité du cadre: protection contre les vulnérabilités. Mar 28, 2025 pm 05:11 PM

L'article traite des fonctionnalités de sécurité essentielles dans les cadres pour se protéger contre les vulnérabilités, notamment la validation des entrées, l'authentification et les mises à jour régulières.

Comment envoyer une demande post contenant des données JSON à l'aide de la bibliothèque Curl de PHP? Comment envoyer une demande post contenant des données JSON à l'aide de la bibliothèque Curl de PHP? Apr 01, 2025 pm 03:12 PM

Envoyant des données JSON à l'aide de la bibliothèque Curl de PHP dans le développement de PHP, il est souvent nécessaire d'interagir avec les API externes. L'une des façons courantes consiste à utiliser la bibliothèque Curl pour envoyer le post� ...

Frameworks de personnalisation / d'extension: comment ajouter des fonctionnalités personnalisées. Frameworks de personnalisation / d'extension: comment ajouter des fonctionnalités personnalisées. Mar 28, 2025 pm 05:12 PM

L'article examine l'ajout de fonctionnalités personnalisées aux cadres, en se concentrant sur la compréhension de l'architecture, l'identification des points d'extension et les meilleures pratiques pour l'intégration et le débogage.

Quelle est exactement la caractéristique non bloquante de ReactPHP? Comment gérer ses opérations d'E / S de blocage? Quelle est exactement la caractéristique non bloquante de ReactPHP? Comment gérer ses opérations d'E / S de blocage? Apr 01, 2025 pm 03:09 PM

Une introduction officielle à la caractéristique non bloquante de l'interprétation approfondie de ReactPHP de la caractéristique non bloquante de ReactphP a suscité de nombreux développeurs: "ReactPhpisnon-blockingByDefault ...

See all articles