说明:$maxwidth和$maxheight只能传递一个,如果传最大宽度将自动计算高度,如果传最大高度将自动计算宽度.
返 回 值:如果创建成功返回文件保存的地址,否则返回false.
php 创建等比例图片代码如下:
- <?php
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- function createSmallImg($dir,$source_img,$small_ex="_s",$maxwidth='',$maxheight='') {
- if(!emptyempty($maxwidth) && !emptyempty($maxheight)) {
- return false;
- }
- $img_name=substr($source_img,0,-4);
- $img_ex = strtolower(substr(strrchr($source_img,"."),1));
-
-
-
-
- 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(!emptyempty($maxheight) && $old_height>=$maxheight) {
- $new_height=$maxheight;
- $new_width=round(($old_width*$new_height)/$old_height);
- } elseif(!emptyempty($maxwidth) && $old_width>=$maxwidth) {
- $new_width=$maxwidth;
- $new_height=round(($old_height*$new_width)/$old_width);
- }
- if(!emptyempty($new_width) || !emptyempty($new_height)) {
- if($img_ex=="jpg" || $img_ex=="png") {
- $dst_img=imagecreatetruecolor($new_width,$new_height);
- } else {
- $dst_img=imagecreate($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;
- }
- ?>
|