php分享对图片大小(缩放)进行调整的函数
|
改变图片的尺寸是一个很常见的功能需求,可以再客户端利用HTML或css来修改图片尺寸,但这种方法可能会使图片变形。最好的方法当然是在服务器端对图片进行剪切操作,操作为自己需要的尺寸。下面开始研究下关于PHP改变图片尺寸的方法。先介绍二个自己写的函数。 函数一: 使用以下代码修改图片大小或创建缩略图。 参数说明: $filename:文件名。 $tmpname:文件路径,如上传中的临时目录。 $xmax:修改后最大宽度。 $ymax:修改后最大高度。 // 重置图片文件大小 function resize_image($filename,$tmpname,$xmax,$ymax) { $ext = explode(".",$filename); $ext = $ext[count($ext)-1]; if($ext == "jpg" || $ext == "jpeg") $im = imagecreatefromjpeg($tmpname); elseif($ext == "png") $im = imagecreatefrompng($tmpname); elseif($ext == "gif") $im = imagecreatefromgif($tmpname); $x = imagesx($im); $y = imagesy($im); if($x <= $xmax && $y <= $ymax) return $im; if($x >= $y) { $newx = $xmax; $newy = $newx * $y / $x; } else { $newy = $ymax; $newx = $x / $y * $newy; } $im2 = imagecreatetruecolor($newx,$newy); imagecopyresized($im2,$im,floor($newx),floor($newy),$x,$y); return $im2; } ?> 函数二: $imgsrc = "http://www.manongjc.com/images/3.jpg"; $width = 780; $height = 420; resizejpg($imgsrc,$imgdst,$width,$height); function resizejpg($imgsrc,$imgwidth,$imgheight) { //$imgsrc jpg格式图像路径 $imgdst jpg格式图像保存文件名 $imgwidth要改变的宽度 $imgheight要改变的高度 //取得图片的宽度,高度值 $arr = getimagesize($imgsrc); header("Content-type: image/jpg"); $imgWidth = $imgwidth; $imgHeight = $imgheight; // Create image and define colors $imgsrc = imagecreatefromjpeg($imgsrc); $image = imagecreatetruecolor($imgWidth,$imgHeight); //创建一个彩色的底图 imagecopyresampled($image,$imgsrc,$imgWidth,$imgHeight,$arr[0],$arr[1]); imagepng($image); imagedestroy($image); } ?> 一个简单的示例:// The file $filename = 'test.jpg'; $percent = 0.5; // Content type header('Content-Type: image/jpeg'); // Get new dimensions list($width,$height) = getimagesize($filename); $new_width = $width * $percent; $new_height = $height * $percent; // Resample $image_p = imagecreatetruecolor($new_width,$new_height); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p,$image,$new_width,$new_height,$height); // Output imagejpeg($image_p,null,100); ?> (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
