0

0

PHP如何生成自适应大小的缩略图

php中文网

php中文网

发布时间:2016-07-25 09:12:55

|

1144人浏览过

|

来源于php中文网

原创

生成缩略图的php类,新建一个文件叫做 thumbnailimage.php,文件名最好不要用大写。

  1. define ( 'MAX_IMG_SIZE', 100000 );
  2. // Supported image types
  3. define ( 'THUMB_JPEG', 'image/jpeg' );
  4. define ( 'THUMB_PNG', 'image/png' );
  5. define ( 'THUMB_GIF', 'image/gif' );
  6. // Interlacing modes
  7. define ( 'INTERLACE_OFF', 0 );
  8. define ( 'INTERLACE_ON', 1 );
  9. // Output modes
  10. define ( 'STDOUT', '' );
  11. // Empty constants
  12. define ( 'NO_LOGO', '' );
  13. define ( 'NO_LABEL', '' );
  14. // Logo and label positioning
  15. define ( 'POS_LEFT', 0 );
  16. define ( 'POS_RIGHT', 1 );
  17. define ( 'POS_CENTER', 2 );
  18. define ( 'POS_TOP', 3 );
  19. define ( 'POS_BOTTOM', 4 );
  20. // Error messages
  21. define ( 'E_001', 'File %s do not exist' );
  22. define ( 'E_002', 'Failed reading image data from %s' );
  23. define ( 'E_003', 'Cannot create the copy of %s' );
  24. define ( 'E_004', 'Cannot copy the logo image' );
  25. define ( 'E_005', 'Cannot create final image' );
  26. // ****************************************************************************
  27. // CLASS DEFINITION
  28. // ****************************************************************************
  29. class ThumbnailImage
  30. {
  31. // ****************************************************************************
  32. // PUBLIC PROPERTIES
  33. // ****************************************************************************
  34. var $src_file; // source image file
  35. var $dest_file; // destination image file
  36. var $dest_type; // destination image type
  37. var $interlace; // destination image interlacing mode
  38. var $jpeg_quality; // quality of resulting JPEG
  39. var $max_width; // maximal thumbnail width
  40. var $max_height; // maximal thumbnail height
  41. var $fit_to_max; // enlarge small images?
  42. var $logo; // array of logo parameters
  43. var $label; // array of label parameters
  44. // ****************************************************************************
  45. // CLASS CONSTRUCTOR
  46. // ****************************************************************************
  47. /*
  48. Description:
  49. Defines default values for properties.
  50. Prototype:
  51. void ThumbImg ( string src_file = '' )
  52. Parameters:
  53. src_file - source image filename
  54. */
  55. function ThumbnailImage ( $src_file = '' )
  56. {
  57. $this->src_file = $src_file;
  58. $this->dest_file = STDOUT;
  59. $this->dest_type = THUMB_JPEG;
  60. $this->interlace = INTERLACE_OFF;
  61. $this->jpeg_quality = -1;
  62. $this->max_width = 100;
  63. $this->max_height = 90;
  64. $this->fit_to_max = FALSE;
  65. $this->logo['file'] = NO_LOGO;
  66. $this->logo['vert_pos'] = POS_TOP;
  67. $this->logo['horz_pos'] = POS_LEFT;
  68. $this->label['text'] = NO_LABEL;
  69. $this->label['vert_pos'] = POS_BOTTOM;
  70. $this->label['horz_pos'] = POS_RIGHT;
  71. $this->label['font'] = '';
  72. $this->label['size'] = 20;
  73. $this->label['color'] = '#000000';
  74. $this->label['angle'] = 0;
  75. }
  76. // ****************************************************************************
  77. // PRIVATE METHODS
  78. // ****************************************************************************
  79. /*
  80. Description:
  81. Extracts decimal color components from hex color string.
  82. Prototype:
  83. array ParseColor ( string hex_color )
  84. Parameters:
  85. hex_color - color in '#rrggbb' format
  86. Return:
  87. Decimal values for red, green and blue color components.
  88. */
  89. function ParseColor ( $hex_color )
  90. {
  91. if ( strpos ( $hex_color, '#' ) === 0 )
  92. $hex_color = substr ( $hex_color, 1 );
  93. $r = hexdec ( substr ( $hex_color, 0, 2 ) );
  94. $g = hexdec ( substr ( $hex_color, 2, 2 ) );
  95. $b = hexdec ( substr ( $hex_color, 4, 2 ) );
  96. return array ( $r, $g, $b );
  97. }
  98. /*
  99. Description:
  100. Retrives image data as a string.
  101. Thanks to Luis Larrateguy for the idea of this function.
  102. Prototype:
  103. string GetImageStr ( string image_file )
  104. Parameters:
  105. image_file - filename of image
  106. Return:
  107. Image file contents string.
  108. */
  109. function GetImageStr ( $image_file )
  110. {
  111. if ( function_exists ( 'file_get_contents' ) )
  112. {
  113. $str = @file_get_contents ( $image_file );
  114. if ( ! $str )
  115. {
  116. $err = sprintf( E_002, $image_file );
  117. trigger_error( $err, E_USER_ERROR );
  118. }
  119. return $str;
  120. }
  121. $f = fopen ( $image_file, 'rb' );
  122. if ( ! $f )
  123. {
  124. $err = sprintf( E_002, $image_file );
  125. trigger_error( $err, E_USER_ERROR );
  126. }
  127. $fsz = @filesize ( $image_file );
  128. if ( ! $fsz )
  129. $fsz = MAX_IMG_SIZE;
  130. $str = fread ( $f, $fsz );
  131. fclose ( $f );
  132. return $str;
  133. }
  134. /*
  135. Description:
  136. Loads image from file.
  137. Prototype:
  138. resource LoadImage ( string image_file, int &image_width, int &image_height )
  139. Parameters:
  140. image_file - filename of image
  141. image_width - width of loaded image
  142. image_height - height of loaded image
  143. Return:
  144. Image identifier representing the image obtained from the given file.
  145. */
  146. function LoadImage ( $image_file, &$image_width, &$image_height )
  147. {
  148. $image_width = 0;
  149. $image_height = 0;
  150. $image_data = $this->GetImageStr( $image_file );
  151. $image = imagecreatefromstring ( $image_data );
  152. if ( ! $image )
  153. {
  154. $err = sprintf( E_003, $image_file );
  155. trigger_error( $err, E_USER_ERROR );
  156. }
  157. $image_width = imagesx ( $image );
  158. $image_height = imagesy ( $image );
  159. return $image;
  160. }
  161. /*
  162. Description:
  163. Calculates thumbnail image sizes from source image width and height.
  164. Prototype:
  165. array GetThumbSize ( int src_width, int src_height )
  166. Parameters:
  167. src_width - width of source image
  168. src_height - height of source image
  169. Return:
  170. An array with 2 elements. Index 0 contains the width of thumbnail image
  171. and index 1 contains the height.
  172. */ 生成缩略图
  173. function GetThumbSize ( $src_width, $src_height )
  174. {
  175. $max_width = $this->max_width;
  176. $max_height = $this->max_height;
  177. $x_ratio = $max_width / $src_width;
  178. $y_ratio = $max_height / $src_height;
  179. $is_small = ( $src_width
  180. if ( ! $this->fit_to_max && $is_small )
  181. {
  182. $dest_width = $src_width;
  183. $dest_height = $src_height;
  184. }
  185. elseif ( $x_ratio * $src_height
  186. {
  187. $dest_width = $max_width;
  188. $dest_height = ceil ( $x_ratio * $src_height );
  189. }
  190. else
  191. {
  192. $dest_width = ceil ( $y_ratio * $src_width );
  193. $dest_height = $max_height;
  194. }
  195. return array ( $dest_width, $dest_height );
  196. }
  197. /*
  198. Description:
  199. Adds logo image to thumbnail.
  200. Prototype:
  201. void AddLogo ( int thumb_width, int thumb_height, resource &thumb_img )
  202. Parameters:
  203. thumb_width - width of thumbnail image
  204. thumb_height - height of thumbnail image
  205. thumb_img - thumbnail image identifier
  206. */
  207. function AddLogo ( $thumb_width, $thumb_height, &$thumb_img )
  208. {
  209. extract ( $this->logo );
  210. $logo_image = $this->LoadImage ( $file, $logo_width, $logo_height );
  211. if ( $vert_pos == POS_CENTER )
  212. $y_pos = ceil ( $thumb_height / 2 - $logo_height / 2 );
  213. elseif ($vert_pos == POS_BOTTOM)
  214. $y_pos = $thumb_height - $logo_height;
  215. else
  216. $y_pos = 0;
  217. if ( $horz_pos == POS_CENTER )
  218. $x_pos = ceil ( $thumb_width / 2 - $logo_width / 2 );
  219. elseif ( $horz_pos == POS_RIGHT )
  220. $x_pos = $thumb_width - $logo_width;
  221. else
  222. $x_pos = 0;
  223. if ( ! imagecopy ( $thumb_img, $logo_image, $x_pos, $y_pos, 0, 0,
  224. $logo_width, $logo_height ) )
  225. trigger_error( E_004, E_USER_ERROR );
  226. }
  227. /*
  228. Description:
  229. Adds label text to thumbnail.
  230. Prototype:
  231. void AddLabel ( int thumb_width, int thumb_height, resource &thumb_img )
  232. Parameters:
  233. thumb_width - width of thumbnail image
  234. thumb_height - height of thumbnail image
  235. thumb_img - thumbnail image identifier
  236. */
  237. function AddLabel ( $thumb_width, $thumb_height, &$thumb_img )
  238. {
  239. extract ( $this->label );
  240. list( $r, $g, $b ) = $this->ParseColor ( $color );
  241. $color_id = imagecolorallocate ( $thumb_img, $r, $g, $b );
  242. $text_box = imagettfbbox ( $size, $angle, $font, $text );
  243. $text_width = $text_box [ 2 ] - $text_box [ 0 ];
  244. $text_height = abs ( $text_box [ 1 ] - $text_box [ 7 ] );
  245. if ( $vert_pos == POS_TOP )
  246. $y_pos = 5 + $text_height;
  247. elseif ( $vert_pos == POS_CENTER )
  248. $y_pos = ceil( $thumb_height / 2 - $text_height / 2 );
  249. elseif ( $vert_pos == POS_BOTTOM )
  250. $y_pos = $thumb_height - $text_height;
  251. if ( $horz_pos == POS_LEFT )
  252. $x_pos = 5;
  253. elseif ( $horz_pos == POS_CENTER )
  254. $x_pos = ceil( $thumb_width / 2 - $text_width / 2 );
  255. elseif ( $horz_pos == POS_RIGHT )
  256. $x_pos = $thumb_width - $text_width -5;
  257. imagettftext ( $thumb_img, $size, $angle, $x_pos, $y_pos,
  258. $color_id, $font, $text );
  259. }
  260. /*
  261. Description:
  262. Output thumbnail image into the browser.
  263. Prototype:
  264. void OutputThumbImage ( resource dest_image )
  265. Parameters:
  266. dest_img - thumbnail image identifier
  267. */ 输出缩略图
  268. function OutputThumbImage ( $dest_image )
  269. {
  270. imageinterlace ( $dest_image, $this->interlace );
  271. header ( 'Content-type: ' . $this->dest_type );
  272. if ( $this->dest_type == THUMB_JPEG )
  273. imagejpeg ( $dest_image, '', $this->jpeg_quality );
  274. elseif ( $this->dest_type == THUMB_GIF )
  275. imagegif($dest_image);
  276. elseif ( $this->dest_type == THUMB_PNG )
  277. imagepng ( $dest_image );
  278. }
  279. /*
  280. Description:
  281. Save thumbnail image into the disc file.
  282. Prototype:
  283. void SaveThumbImage ( string image_file, resource dest_image )
  284. Parameters:
  285. image_file - destination file name
  286. dest_img - thumbnail image identifier
  287. */
  288. function SaveThumbImage ( $image_file, $dest_image )
  289. {
  290. imageinterlace ( $dest_image, $this->interlace );
  291. if ( $this->dest_type == THUMB_JPEG )
  292. imagejpeg ( $dest_image, $this->dest_file, $this->jpeg_quality );
  293. elseif ( $this->dest_type == THUMB_GIF )
  294. imagegif ( $dest_image, $this->dest_file );
  295. elseif ( $this->dest_type == THUMB_PNG )
  296. imagepng ( $dest_image, $this->dest_file );
  297. }
  298. // ****************************************************************************
  299. // PUBLIC METHODS
  300. // ****************************************************************************
  301. /*
  302. Description:
  303. Output thumbnail image into the browser or disc file according to the
  304. values of parameters.
  305. Prototype:
  306. void Output ( )
  307. */ 生成缩略图片
  308. function Output()
  309. {
  310. $src_image = $this->LoadImage($this->src_file, $src_width, $src_height);
  311. $dest_size = $this->GetThumbSize($src_width, $src_height);
  312. $dest_width=$dest_size[0];
  313. $dest_height=$dest_size[1];
  314. $dest_image=imagecreatetruecolor($dest_width, $dest_height);
  315. if (!$dest_image)
  316. trigger_error(E_005, E_USER_ERROR);
  317. imagecopyresampled( $dest_image, $src_image, 0, 0, 0, 0,
  318. $dest_width, $dest_height, $src_width, $src_height );
  319. if ($this->logo['file'] != NO_LOGO)
  320. $this->AddLogo($dest_width, $dest_height, $dest_image);
  321. if ($this->label['text'] != NO_LABEL)
  322. $this->AddLabel($dest_width, $dest_height, $dest_image);
  323. if ($this->dest_file == STDOUT)
  324. $this->OutputThumbImage ( $dest_image );
  325. else
  326. $this->SaveThumbImage ( $this->dest_file, $dest_image );
  327. imagedestroy ( $src_image );
  328. imagedestroy ( $dest_image );
  329. }
  330. } // End of class definition
  331. ?>
复制代码

使用方法: 1、首先引用该php文件(不要告诉我不会) 2、调用代码

  1. $tis = new ThumbnailImage();
  2. $tis->src_file = "这里写源文件的路径"
  3. $tis->dest_type = THUMB_JPEG;//生成图片的类型是 jpg
  4. $tis->dest_file = '这里写目标文件的路径';
  5. $tis->max_width = 120;//自适应大小,但是最大宽度为120
  6. $tis->max_height = 4000; //自适应大小,但是最大高度为4000
  7. $tis->Output();
复制代码

代码关键在于: max_width 和max_height, 一般来说除非图片很有个性,否则缩略图生成的还是很不错的。



相关文章

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法
pixiv网页版官网登录与阅读指南_pixiv官网直达入口与在线访问方法

本专题系统整理pixiv网页版官网入口及登录访问方式,涵盖官网登录页面直达路径、在线阅读入口及快速进入方法说明,帮助用户高效找到pixiv官方网站,实现便捷、安全的网页端浏览与账号登录体验。

928

2026.02.13

微博网页版主页入口与登录指南_官方网页端快速访问方法
微博网页版主页入口与登录指南_官方网页端快速访问方法

本专题系统整理微博网页版官方入口及网页端登录方式,涵盖首页直达地址、账号登录流程与常见访问问题说明,帮助用户快速找到微博官网主页,实现便捷、安全的网页端登录与内容浏览体验。

307

2026.02.13

Flutter跨平台开发与状态管理实战
Flutter跨平台开发与状态管理实战

本专题围绕Flutter框架展开,系统讲解跨平台UI构建原理与状态管理方案。内容涵盖Widget生命周期、路由管理、Provider与Bloc状态管理模式、网络请求封装及性能优化技巧。通过实战项目演示,帮助开发者构建流畅、可维护的跨平台移动应用。

183

2026.02.13

TypeScript工程化开发与Vite构建优化实践
TypeScript工程化开发与Vite构建优化实践

本专题面向前端开发者,深入讲解 TypeScript 类型系统与大型项目结构设计方法,并结合 Vite 构建工具优化前端工程化流程。内容包括模块化设计、类型声明管理、代码分割、热更新原理以及构建性能调优。通过完整项目示例,帮助开发者提升代码可维护性与开发效率。

29

2026.02.13

Redis高可用架构与分布式缓存实战
Redis高可用架构与分布式缓存实战

本专题围绕 Redis 在高并发系统中的应用展开,系统讲解主从复制、哨兵机制、Cluster 集群模式及数据分片原理。内容涵盖缓存穿透与雪崩解决方案、分布式锁实现、热点数据优化及持久化策略。通过真实业务场景演示,帮助开发者构建高可用、可扩展的分布式缓存系统。

103

2026.02.13

c语言 数据类型
c语言 数据类型

本专题整合了c语言数据类型相关内容,阅读专题下面的文章了解更多详细内容。

54

2026.02.12

雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法
雨课堂网页版登录入口与使用指南_官方在线教学平台访问方法

本专题系统整理雨课堂网页版官方入口及在线登录方式,涵盖账号登录流程、官方直连入口及平台访问方法说明,帮助师生用户快速进入雨课堂在线教学平台,实现便捷、高效的课程学习与教学管理体验。

17

2026.02.12

豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法
豆包AI网页版入口与智能创作指南_官方在线写作与图片生成使用方法

本专题汇总豆包AI官方网页版入口及在线使用方式,涵盖智能写作工具、图片生成体验入口和官网登录方法,帮助用户快速直达豆包AI平台,高效完成文本创作与AI生图任务,实现便捷智能创作体验。

764

2026.02.12

PostgreSQL性能优化与索引调优实战
PostgreSQL性能优化与索引调优实战

本专题面向后端开发与数据库工程师,深入讲解 PostgreSQL 查询优化原理与索引机制。内容包括执行计划分析、常见索引类型对比、慢查询优化策略、事务隔离级别以及高并发场景下的性能调优技巧。通过实战案例解析,帮助开发者提升数据库响应速度与系统稳定性。

92

2026.02.12

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
PHP水印与缩略图最新视频教程
PHP水印与缩略图最新视频教程

共10课时 | 1.8万人学习

JavaScript OOP调试技巧视频教程
JavaScript OOP调试技巧视频教程

共5课时 | 1.0万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号