php有专门处理图片的函数,对于一些要求较高的图片缩放,php也能做到。
首先使用一个ini文件来设置要缩放的大小,其中为宽或高0的则为图片放大或缩小,都为0则还是原大小,都不为0都拉抻成指定的大小。
注意:ini文件使用php解释时为注释文件,什么也没有输出,这是为了安全起见而故意为之。而;则是ini文件的注释。
我设置的ini文件例子如下:
<?php /*
;Translate the image format using the original image size
[Translation]
width=0
height=0
;Stretch the image to the specified size
[Stretch]
width=800
height=600
;Zoom the image to the specified Width with height auto size
[AutoHeight]
width=740
height=0
;Zoom the image to the specified Height with width auto size
[AutoWidth]
width=0
height=380
*/ ?>
下面是编写的缩放图片的php代码,其中变量classes是一个数组,可以选择任意多个ini文件中指定的设置:
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 | <?php $oimg = "test.jpg" ; //Original image name $classes = array ( 'Translation' , 'AutoHeight' , 'AutoWidth' , 'Stretch' ); //Give classes for the new creating images' size which are defined in the specified ini file $suffix = 'jpg' ; //The new image's suffix $inifile = 'image.ini.php' ; $size = getimagesize ( $oimg ); $x = $size [0]/ $size [1]; $name = explode ( '.' , $oimg ); if (! file_exists ( $inifile )) die ( 'Ini file does not exist!' ); $cn = parse_ini_file ( $inifile ,true); //Parse the class style image size from ini file foreach ( $classes as $class ){ foreach ( $cn as $k => $v ){ if ( $k == $class ){ if ( $v [ 'width' ] && $v [ 'height' ]){ $thumbWidth = $v [ 'width' ]; $thumbHeight = $v [ 'height' ]; } elseif ( $v [ 'width' ]){ $thumbWidth = $v [ 'width' ]; $thumbHeight = round ( $thumbWidth / $x ); } elseif ( $v [ 'height' ]){ $thumbHeight = $v [ 'height' ]; $thumbWidth = round ( $thumbHeight * $x ); } else { $thumbWidth = $size [0]; $thumbHeight = $size [1]; } break ; } } if (!isset( $thumbHeight ) && !isset( $thumbWidth )) die ( 'Ini file Settings error!' ); $nimg = $name [0]. '_' . $class . '.' . $suffix ; //New image file name $source = imagecreatefromjpeg( $oimg ); $thumb = imagecreatetruecolor( $thumbWidth , $thumbHeight ); imagecopyresampled( $thumb , $source ,0,0,0,0, $thumbWidth , $thumbHeight , $size [0], $size [1]); if ( $suffix == 'jpg' ) $method = 'imagejpeg' ; else $method = 'image' . $suffix ; $method ( $thumb , $nimg ); imagedestroy( $thumb ); //Release the image source imagedestroy( $source ); } ?> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?