用PHP生成等比图像的方法
PHP代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | <?php /************************************************************************ * 函数名称:createSmallImg() * 函数说明:创建等比例图片 * 输入参数: $dir 保存路径 $source_img 原图片名称 $small_ex 缩率图文件名后缀 $maxwidth 最大宽度 $maxheight 最大高度 * 说 明:$maxwidth和$maxheight只能传递一个,如果传最大宽度将自动计算高度,如果传最大高度将自动计算宽度 * 返 回 值:如果创建成功返回文件保存的地址,否则返回false * 编 写 者:李小宇 * 编写时间:2011/8/18 **************************************************************************/ function createSmallImg( $dir , $source_img , $small_ex = "_s" , $maxwidth = '' , $maxheight = '' ) { if (! empty ( $maxwidth ) && ! empty ( $maxheight )) { return false; } $img_name = substr ( $source_img ,0,-4); $img_ex = strtolower ( substr ( strrchr ( $source_img , "." ),1)); /*注释的这段用作直接在浏览器上显示图片 $im=imagecreatefromjpeg($file); header("Content-type: image/jpeg"); imagejpeg($im);*/ switch ( $img_ex ) { case "jpg" : $src_img =imagecreatefromjpeg( $dir . $source_img ); break ; case "gif" : $src_img =imagecreatefromgif( $dir . $source_img ); break ; case "png" : $src_img =imagecreatefrompng( $dir . $source_img ); break ; } $old_width =imagesx( $src_img ); $old_height =imagesy( $src_img ); if (! empty ( $maxheight ) && $old_height >= $maxheight ) { $new_height = $maxheight ; $new_width = round (( $old_width * $new_height )/ $old_height ); } elseif (! empty ( $maxwidth ) && $old_width >= $maxwidth ) { $new_width = $maxwidth ; $new_height = round (( $old_height * $new_width )/ $old_width ); } if (! empty ( $new_width ) || ! empty ( $new_height )) { $dst_img =imagecreatetruecolor( $new_width , $new_height ); imagecopyresampled( $dst_img , $src_img ,0,0,0,0, $new_width , $new_height , $old_width , $old_height ); $smallname = $dir . $img_name . $small_ex . "." . $img_ex ; switch ( $img_ex ) { case "jpg" : imagejpeg( $dst_img , $smallname ,100); break ; case "gif" : imagegif( $dst_img , $smallname ); break ; case "png" : imagepng( $dst_img , $smallname ); break ; } } return $smallname ; } |
imagecopyresampled比imagecopyresized生成的图片更清晰
重采样拷贝部分图像并调整大小
imagecopyresampled() 将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。成功时返回 TRUE, 或者在失败时返回 FALSE.
分类:
PHP
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何在 .NET 中 使用 ANTLR4
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 想让你多爱自己一些的开源计时器
· Cursor预测程序员行业倒计时:CTO应做好50%裁员计划
· 大模型 Token 究竟是啥:图解大模型Token
· 用99元买的服务器搭一套CI/CD系统
· 如何在 .NET 中 使用 ANTLR4